home *** CD-ROM | disk | FTP | other *** search
/ Scene Storm / Scene Storm - Volume 1.iso / coding / asm_reference / amigaocs_hardware.doc < prev    next >
Text File  |  1995-09-01  |  208KB  |  4,792 lines

  1.  
  2.  
  3.  
  4. This is my hardware DOC file. It bears no relation to the stuff in any of
  5. the Amiga manuals to my knowledge, but draws from the Amiga System Pro-
  6. grammer's Guide by Abacus for much important material. Also, I include some
  7. example pieces of code of my own, routines plus data structures, illustra-
  8. ting how to manipulate the hardware directly.
  9.  
  10.  
  11. List of Topics:
  12.  
  13.  
  14. Hardware:Preamble
  15. Hardware:The CIA Chips
  16. Hardware:DMA
  17. Hardware:Interrupts
  18. Hardware:The Copper
  19. Hardware:Bitplanes & Bitplane Control
  20. Hardware:Sprite Management
  21. Hardware:The Blitter
  22. Hardware:Sound Management
  23. Hardware:Disc Management
  24. Hardware:Interfaces
  25. Hardware:Mouse, Keyboard, Joysticks
  26. Hardware:Some Notes
  27. Hardware:Logic Tutorial (for mathematically skilled readers & masochists)
  28.  
  29.  
  30. Hardware:Preamble
  31.  
  32.  
  33. This DOC file is somewhat oddly organised. This is because several different
  34. sections contain material that cross-references across topic headings. Where
  35. a cross-reference exists, I'll signpost it using the # character followed
  36. by a number. If you use Devpac to view this file, you can skip across the
  37. cross-references using the search facility.
  38.  
  39.     The main base addresses for the chips are $BFD000 and $BFE001 for
  40. the CIAs, and $DFF000 for the gee-whizz custom chips. The custom chips are
  41. organised as a linear block of word addresses from the base address onwards,
  42. and the CIA register addresses occur at 256-byte intervals from the base add-
  43. ress onwards. Other than that, there will occur extra pieces of information
  44. relating the way that several of the chips are connected to various hardware
  45. interfaces such as the keyboard and mouse. They are the main reason for the
  46. implementation of the cross-referencing scheme in this file, because in the
  47. case of the CIAs, they are connected to several different actual hardware
  48. interfaces.
  49.  
  50.     I find it best to use instructions of the form
  51.  
  52.  
  53.         MOVE.W    #DATA,register(A0)
  54.  
  55.  
  56. when accessing the chips, because there's less time overhead than with those
  57. instructions using absolute addresses. In the above case, A0 contains the
  58. base address of the chip set being accessed.
  59.  
  60.     One more point. The 68000 CLR instruction issues a read access and
  61. then a write access singal across its bus. Other 680x0 chips from the 68020
  62. onwwards perform a single write access only. Because of this, using something
  63. like CLR COPJMP1(A0) is not recommended, even though it's shorter than using
  64. MOVE.W #0,COPJMP1(A0), when accessing strobe registers (see later for an ex-
  65. planation of what these are). Those blessed with assemblers capable of gen-
  66. erating 68020/68030/68040 code and inline coprocessor code for the 68881 and
  67. 68882 maths coprocessors should NOT use these facilities when accessing the
  68. custom chips in particular if they're lucky enough to have a 680x0 acceler-
  69. ator board fitted. Save these facilities for accelerator-board specific code
  70. only. Also be warned about invalid cache entry on these processors if the DMA
  71. from the custom chips scribbles all over memory when the accelerator board
  72. processor is attempting an access at that address range!
  73.  
  74.     Given the propensity of games writers in particular to tell AmigaDos
  75. to take a hike, I issue the following caveats:using MOVE to SR to kill off
  76. iterrupts doesn't work properly-the interrupts are handled by the 4703 custom
  77. chip and generated anyway. All that happens is that the 68000 ignores them,
  78. and the relevant bits in the 4703 control registers don't get handled proper-
  79. ly. This can cause problems. Also, supervisor mode doesn't provide any real
  80. advantages over user mode (although I'm guilty of abusing it sometimes). If
  81. you're handling your own exceptions directly, take account of differences in
  82. exception stack frames especially if you've got a 680x0 accelerator board! I
  83. recently found out that a gee-whizz 68040 board is now available with 2 megs
  84. of memory from a company in Pasadena. £2000 and it's yours. Also, if you are
  85. the sort of programmer who pees around with the ROM, watch out!
  86.  
  87.     One final point. To save typing out addresses of the form $DFFxxx in
  88. full for custom chip register addresses, I'll refer to them via offsets from
  89. the base address of $DFF000. It's a VERY GOOD idea to do this in programs as
  90. well! Load, say, A5 with $DFF000 and access the register of your choice using
  91. something like
  92.  
  93.         MOVE.W    #DATA,REGISTER_NAME(A5)
  94.  
  95. instead of littering code with absolute addresses (you'll also save 4 cycles
  96. of processor time per access!). Any persons having encountered the dread set
  97. of files called 'my_hardware.i' etc., which I have created for my own use &
  98. recently distributed to others will find all of the custom chip registers in
  99. name form defined as offset equates from the base address of $DFF000, and any
  100. programs using these include files accessing the custom chips in the manner
  101. above. 
  102.  
  103.  
  104. Hardware:The CIA Chips
  105.  
  106.  
  107. There are two of these beasties on the Amiga. They're referred to as CIA-A &
  108. CIA-B respectively. CIA-A lives at $BFE001 onwards, CIA-B at $BFD000 on. I
  109. now present the register list. The formula for the address of each register
  110. is register number*256+CIA base address, and all CIA registers are a
  111. single byte wide.
  112.  
  113.  
  114.     Register        Name
  115.     --------        ----
  116.  
  117.        0        PRA (Port A Data Register) R/W
  118.        1        PRB (Port B Data Register)    R/W
  119.        2        DDRA (Port A Data Direction Register) R/W
  120.        3        DDRB (Port B Data Direction Register) R/W
  121.        4        TALO (Timer A lower 8 bits) R/W
  122.        5        TAHI (Timer A upper 8 bits) R/W
  123.        6        TBLO (Timer B lower 8 bits) R/W
  124.        7        TBHI (Timer B upper 8 bits) R/W
  125.        8        E.LSB (Event counter lower byte) R/W
  126.        9        E.MID (Event counter middle byte) R/W
  127.        A        E.MSB (Event counter high byte) R/W
  128.        B        not used
  129.        C        SP (Serial port data register) R/W
  130.        D        ICR (Interrupt control register) R/W
  131.        E        CRA (Control register A) R/W
  132.        F        CRB (Control register B) R/W
  133.  
  134.  
  135. Note:the 'serial port' on the CIAs is NOT the same as the Amiga serial port
  136. at the back! This is an internal serial port, and on the CIA-A it is connect-
  137. ed to the 6500/1 processor handling the keyboard (#1). The main serial port
  138. for external communications is handled via Paula (#2).
  139.  
  140.  
  141. Data registers:the CIA data registers are connected in a seemingly odd manner
  142. to various different pieces of hardware. They can be treated bitwise as input
  143. or output registers. If the corresponding DDRx bit is 0, the same bit on the
  144. PRx is an input, and an output if the DDRx bit is a 1. Writing to a data reg-
  145. ister stores the value in it, and reading it reads the state of those port
  146. lines to which it is connected.
  147.  
  148.     There is a simple handshaking mechanism via two lines, called PC and
  149. FLAG. PC goes low for 1 clock cycle on each access to PRB. The FLAG input re-
  150. sponds to such transitions. Every time the state of FLAG changes from 1 to 0,
  151. the FLAG bit in the ICR is set. These two lines allow a simple form of hand-
  152. shaking in which the PC and FLAG lines of the CIAs are cross-connected. The
  153. sender need only write its data to the port register & then wait for a FLAG
  154. signal before sending each additional byte. Since FLAG can generate an int-
  155. errupt if wanted, the sender can perform other tasks while waiting for the
  156. FLAG signal, and continue the sending via an interrupt routine. The same also
  157. applies to the receiver, except that it reads the data from the port instead
  158. of writing to it. CIA-A has its PRB connected to the parallel port (more cor-
  159. rectly, the Centronics port data lines), and CIA-B has a whole series of awk-
  160. ward connections for PRB as follows (Cross-reference #6):
  161.  
  162.  
  163.     Bit    Connection
  164.     ---    ----------
  165.      7    /MTR motor signal to disc drive
  166.      6    /SEL3 drive 3 select
  167.      5    /SEL2 drive 2 select
  168.      4    /SEL1 drive 1 select
  169.      3    /SEL0 drive 0 select
  170.      2    /SIDE drive side select
  171.      1    DIR data direction signal to disc drive
  172.      0    /STEP step signal to drive head stepper motor
  173.  
  174.  
  175. Both CIAs have awkward connections for PRA. They are (CIA-A first, then
  176. CIA-B):
  177.  
  178.  
  179.     Bit    Connection
  180.     ---    ----------
  181.      7    Game port 1 pin 6 (fire button)
  182.      6    Game port 0 pin 6 (fire button)
  183.      5    /RDY disc ready signal from disc drive
  184.      4    /TK0 disc track 00 signal from disc drive
  185.      3    /WRPO write protect signal from disc drive
  186.      2    /CHNG disc change signal from disc drive
  187.      1    LED power LED (0=on, 1=off)
  188.      0    OVL memory overlay bit (DANGER!!!!)
  189.  
  190.      7    /DTR DTR signal from serial interface
  191.      6    /RTS RTS signal from serial interface
  192.      5    /CD  CD signal from serial interface
  193.      4    /CTS CTS signal from serial interface
  194.      3    /DSR DSR signal from serial interface
  195.      2    SEL select signal for Centronics interface
  196.      1    POUT paper out signal from Centronics interface
  197.      0    BUSY busy signal from Centronics interface
  198.  
  199.  
  200. When I said the connections were awkward, I wasn't kidding.
  201.  
  202. Control registers:the two control registers determine the mode of operation
  203. of many of the other registers. CRA bit allocations are:
  204.  
  205.  
  206.     Bit    Function
  207.     ---    --------
  208.      7    Not used
  209.      6    SPMOD serial port register mode 0=input, 1=output
  210.      5    INMODE 0=clock, 1=CNT (see later)
  211.      4    LOAD 1=force load (strobe) for timer A
  212.      3    RUNMODE 0=continuous, 1=one-shot for timer A
  213.      2    OUTMODE 0=pulse, 1=toggle
  214.      1    PBON 0=PB6 off, 1=PB6 on
  215.      0    START 0=off, 1=on
  216.  
  217.  
  218. CRB bit allocations are:
  219.  
  220.  
  221.     Bit    Function
  222.     ---    --------
  223.      7    0=TOD (time of day-see later), 1=ALARM
  224.     6,5    INMODE
  225.         00 = clock, 01=CNT
  226.         10 = timer A input,
  227.         11 = timer A + CNT
  228.  
  229.      4    LOAD 1=force load (strobe) for timer A
  230.      3    RUNMODE 0=continuous, 1=one-shot for timer A
  231.      2    OUTMODE 0=pulse, 1=toggle
  232.      1    PBON 0=PB7 off, 1=PB7 on
  233.      0    START 0=off, 1=on
  234.  
  235.  
  236. Timers:this is one of the complicated things. These timers can count down
  237. from a preset value to zero. When reading, they are treated as TALO/TAHI
  238. and TBLO/TBHI. When writing, they are treated as latches PALO/PAHI and
  239. PBLO/PBHI. The latches should be loaded, low byte first, as a write access
  240. to the high register causes the timer to be stopped and reloaded with the
  241. latch value unless the LOAD bit in the control register is set, in which case
  242. the latch value is transferred to the timers regardless of the timer state.
  243. The LOAD bit in the CRA/CRB registers is a strobe bit. Writing simply causes
  244. the given action to be performed-the bit value is not stored as such.
  245.  
  246.     When the timer hits zero, the latch values are automatically put
  247. back into the timer.
  248.  
  249.     The latch is also known as the prescaler. The number of timeouts in
  250. continuous mode is equal to the clock frequency divided by the value in the
  251. prescaler/latch. Timer A is connected to the processor E clock, the frequency
  252. being 716KHz.
  253.  
  254.     Reading the timer can cause problems, because it has to be performed
  255. in two separate read operations. One problem is that the timer could change
  256. its state between the two reads. For example, if the timer bytes combined are
  257. $0100 in value, and the high byte is read, the timer could decrement to $00FF
  258. before the low byte is read, resulting in a final read value of $01FF, which
  259. is incorrect (it should be $00FF). Stopping the timer from decrementing
  260. during the read is one method of preventing this, but this is not the most
  261. elegant way. Instead, read the high byte, then the low byte, then read the
  262. high byte again in a separate register. If the two high byte reads are the
  263. same, take this as the value. If not, repeat the process. It should only need
  264. one repeat read to obtain the correct result, but in any case the following
  265. code should obtain the correct value (code is for CIA-A):
  266.  
  267.  
  268.         LEA    $BFE001,A0    ;CIA-A base address
  269.  
  270. get_timer    MOVE.B    $400(A0),D0    ;get TALO
  271.         MOVE.B    $500(A0),D1    ;get TAHI
  272.         MOVE.B    $400(A0),D2    ;get TALO again
  273.         CMP.B    D0,D2        ;timer values match?
  274.         BNE.S    get_timer    ;repeat read if not
  275.  
  276.         NOP            ;here, got correct timer!
  277.  
  278.  
  279. Bits 5 and 6 of the control registers control the timer functions. For timer
  280. A, there are two possibilities. Either CRA INMODE=0, in which case timer A is
  281. decremented during each clock cycle on the processor's E clock line, or else
  282. CRA INMODE=1, in which case each high pulse on the CNT input line decrements
  283. the timer.
  284.  
  285.     Timer B has four possible operating modes, governed by the INMODE
  286. bits of CRB. First there is INMODE mode 00, in which timer B decrements each
  287. time a pulse occurs on the E clock line (connected to the f2 pin of the CIA)
  288. just as for timer A INMODE=0. INMODE=01 decrements timer B every time there
  289. is a pulse on the CNT line. INMODE=10 allows timers A and B to be combined to
  290. form a 32-bit timer, and timer B decrements every time a timeout signal from
  291. timer A is received. In this mode, timer A forms the low word of the 32-bit
  292. timer, and timer B the high word. Finally, INMODE=11 allows the length of a
  293. pulse on the CNT line to be measured. In this mode, timer A issues a timeout
  294. when the CNT line is high. The timeout signals are in the interrupt control
  295. register or ICR, to be dealt with later.
  296.  
  297.     Two output modes for the timers can be selected with the OUTMODE bit
  298. of the control registers. OUTMODE=0 causes timeout signals to appear as a
  299. positive pulse one clock period long on the corresponding port line. When the
  300. OUTMODE=1 (toggle mode), each timeout causes the corresponding port line to
  301. change value from low to high or high to low. Each time the timer is started
  302. in this mode, the output starts as a high signal.
  303.  
  304.     The RUNMODE bit determines whether the timer operates in one-shot
  305. mode (RUNMODE=1) or operates continuously (RUNMODE=0). In one-shot mode, the
  306. timer stops after each timeout and sets the START bit to 0. In the contin-
  307. uous mode the timer restarts after each timeout automatically.
  308.  
  309.     Timer A of CIA-A is used by the operating system for communication
  310. with the keyboard, and timer B by the operating system for some other tasks.
  311. Timer A of CIA-B is used for serial data transfers, otherwise it is free, and
  312. timer B is used to synchronise the blitter with the screen by the OS, other-
  313. wise it is free.
  314.  
  315.  
  316. Interrupt Control:this is actually implemented as two registers, one being a
  317. read register and one being a write register. The bit allocations are given
  318. in the table below, read register first. The read register is the ICR data
  319. register, the write register the ICR enable mask register.
  320.  
  321.  
  322.     Bit        Function
  323.     ---        --------
  324.      7        IR - Interrupt received/signalled
  325.      6        not used, always 0
  326.      5        not used, always 0
  327.      4        FLAG - PRB port handshaking
  328.      3        SP - serial port needs attention
  329.      2        Alarm signal
  330.      1        TB - Timeout for Timer B
  331.      0        TA - Timeout for Timer A
  332.  
  333.  
  334.      7        Set/Clr bit (explained below)
  335.      6        not used, send a 0
  336.      5        not used, send a 0
  337.      4        FLAG input enable
  338.      3        SP - serial port interrupt enable
  339.      2        Alarm input enable
  340.      1        Timer B timeout enable
  341.      0        Timer A timeout enable
  342.  
  343.  
  344. The set/clr bit is used as follows. Let us assume that the byte to be written
  345. to the ICR is %00010011. Bit 7 (the set/clr bit) is 0. This tells the input
  346. latch for the ICR to clear all bits in the ICR write register corresponding
  347. to the 1 bits in the byte just written to it, and to leave all other bits un-
  348. changed. This particular write byte has bits 4,1 and 0 set, so the FLAG, TB
  349. and TA interrupt inputs are disabled. If the byte was %10010011 instead, the
  350. set bit 7 (corresponding to set/clr on the ICR) would tell the input latch
  351. for the ICR to set all bits corresponding to the other 1 bits in the byte
  352. just written, and leave all of the others unchanged. This write byte would
  353. enable the modes disabled by the previous write byte example.
  354.  
  355.     Note that this set/clr mechanism occurs throughout the Amiga chip
  356. set, in particular for DMA control (#3), main system interrupt control (#4)
  357. and other functions.
  358.  
  359.     Having written a control byte to enable various interrupt sources
  360. (CIA-local interrupt sources, NOT main system ones!), we can now read the
  361. same address and the chip will return the value of the ICR data register,
  362. which contains bitwise information about which interrupt source triggered
  363. the CIA's internal interrupt mechanism. Note that any interrupt handled via
  364. the CIAs is further passed onto the system as a whole, to allow 68000 auto-
  365. vectored interrupt code to handle the interrupt. More about this later.
  366.  
  367.     If this value is needed for multiple interrupt source tests, then it
  368. must be saved, because reading the ICR data register causes the CIA to clear
  369. it after the read. The IR bit is the interrupt request bit, and if set, indi-
  370. cates that a valud CIA internal interrupt was triggered. But this and all of
  371. the other ICR data bits are cleared upon reading, so if you fail to save the
  372. result of the read (this code saves the read value);
  373.  
  374.  
  375.         LEA    $BFE001,A0        ;CIA-A base addr
  376.         MOVE.B    $D00(A0),D0        ;get ICR data reg value
  377.         MOVE.B    D0,last_icra_read(A6)    ;save in my variable block!
  378.  
  379.  
  380. and then obliterate the unprocessed bits without saving as above, then you
  381. have lost forever those unprocessed bits. You have been warned!
  382.  
  383.     The CIA signals an interrupt as follows. Whenever one of the various
  384. interrupt sources sets its corresponding bit in the ICR data register, the
  385. CIA checks to see if the corresponding ICR mask enable bit is also set. If
  386. this is so, the CIA pulls the IRQ line low to signal the interrupt in hard-
  387. ware, and then sets the IR bit (bit 7) in the ICR data register to signal the
  388. interrupt in software also. How the main system treats this signal is handled
  389. later. The IRQ line does not return to the high state (its normal state) un-
  390. til the ICR data register is read (and hence the IR bit, and all others, are
  391. cleared by the CIA).
  392.  
  393.  
  394. Event Counter:this event counter differs from the 6526 Time-Of-Day counter
  395. found, for example, in the Commodore 64 (yeuk!). This is almost the only
  396. difference between the 6526 and the 8520 CIA. Those unfortunate enough to
  397. have encountered the 6526 in past programming will breathe a sigh of relief.
  398. There is one slight problem with the documentation that Commodore supply-
  399. they insist on referring to TOD (time of day) in the literature, even though
  400. this term is meaningless here.
  401.  
  402.     Instead of the real-time clock which counts hours, minutes and sec-
  403. onds on the 6526, the 8520 has a simple 24-bit event counter. It takes its
  404. input signal on the TOD line (jeez, Commodore!) of the chip. The event coun-
  405. ter starts at zero (or some other predefined state written to it) and counts
  406. UPWARDS to $FFFFFF, before returning to zero. The event counter consists of
  407. the counter proper and a latch register. When the high byte is read, the ac-
  408. tual counter state is transferred completely to the 24-bit latch, and the
  409. high byte of the latch returned. The counter continues counting undisturbed
  410. while the remaining latch registers are read, mid-byte next, then low-byte.
  411. ALWAYS read in the order high, mid, low or else this won't work!
  412.  
  413.     Writing a value to the event counter causes the CIA to stop the
  414. counter until the entire value is written, PROVIDED that it is written to
  415. in the same order as it is read from above, namely high, mid, low. Once
  416. the low byte is written, the timer starts up again, with the written value
  417. as the start value. When writing the event counter value in normal mode, be
  418. sure that the TOD/ALARM bit of the CRB control register is cleared!
  419.  
  420.     An alarm function exists also. SET the Alarm bit in CRB as opposed
  421. to clearing it as for normal event counter writing, and write a value into
  422. the event counter. The chip will take this value as an alarm value, and if
  423. the event counter value ever matches this alarm value, the alarm bit of the
  424. interrupt control register is set. The value of the alarm setting CANNOT be
  425. read, only written - reading the event counter always returns the current
  426. counter latch value, regardless of the state of the TOD/Alarm bit in CRB. So
  427. if you want to provide known alarm values, save them somewhere safe before
  428. using them!
  429.  
  430.  
  431. Serial Port:the serial port consists of the serial data register (which is
  432. readable and writeable) and the shift register (not directly accessible).
  433. Setting SPMODE=0 in the control register sets the serial port to input mode
  434. and SPMODE=1 to output mode.
  435.  
  436.     In input mode, the serial data on the SP line are shifted into the
  437. shift register after each rising edge on the CNT line. After 8 CNT pulses the
  438. shift register is full, and the data is transferred to the serial data reg-
  439. ister. At the same time, the SP bit in the ICR data register is set. If more
  440. CNT pulses are received, the data continues to shift into the shift register
  441. until it is full again. If the user has read the serial data register before
  442. this, the data is transferred across again, else it is lost. When using this
  443. register for input, respond to it reasonably promptly!
  444.  
  445.     In output mode, timer A is used to determine the send frequency. The
  446. timeout rate of timer A (which must be operated in CONTINUOUS mode) controls
  447. the baud rate of the transfer. The data are shifted out of the shift register
  448. at half the timeout rate of timer A, whereby the maximum output rate is 1/4
  449. of the clock frequency of the 8520.
  450.  
  451.     The transfer begins after the first byte is written to the serial
  452. data register. The CIA transfers the byte into the shift register. The
  453. individual data bits now appear at half the timeout rate of timer A on the
  454. SP line and the clock signal from timer A appears on the CNT line (it changes
  455. value on each timeout so that the next bit appears on the SP line on each
  456. negative transition [high to low] ). The transfer begins with the most sig-
  457. nificant bit of the data byte. Once all 8 bits have been output, the CNT line
  458. remains high and the SP line retains the value of the last bit sent. In add-
  459. ition, the SP bit of the ICR data register is set to show that the serial
  460. data register can be supplied with new data. If the next data byte was loaded
  461. into the data register before the output of the last bit, the data output
  462. will continue without interruption.
  463.  
  464.     To keep the transfer continuous, the serial data register must be
  465. re-supplied with fresh data at the proper time.
  466.  
  467.     The SP and CNT lines are described as 'open-collector' outputs. This
  468. allows the outputs of multiple CIAs to be connected together. See any good
  469. text on electronic interfacing techniques for an explanation (especially the
  470. mass of material on the IEEE-488 bus) of open-collector outputs.
  471.  
  472.     On the Amiga, the SP line of CIA-A is connected to the KDAT line of
  473. the keyboard 6500/1 processor, and the CNT line connected to the KCLK line of
  474. the keyboard processor. So hardware keyboard reads can be performed by enab-
  475. ling serial port interrupts in CIA-A (which AmigaDos does for its own use),
  476. and writing an autovector interrupt routine to intercept the ICR SP signal
  477. and read the serial data register.
  478.  
  479.     The SP of CIA-B is connected to the Centronics BUSY signal (as is
  480. PA0 of the CIA parallel port A) and the CNT line to the Centronics PAPER
  481. OUT signal (as is PA1 of the CIA parallel port A).
  482.  
  483.  
  484. Other Information:other connections for CIA-A are:
  485.  
  486. PC    /DRDY - Centronics handshake, data ready
  487. FLAG    /ACK  - Centronics handshake, data acknowledge
  488. IRQ    /INT2 input from Paula (#2)
  489. RES    /RES reset line
  490.  
  491. and connections for CIA-B are:
  492.  
  493. PC    not used
  494. FLAG    /INDEX - index signal from disc drive
  495. IRQ    /INT6 input from Paula (#2)
  496. RES    /RES reset line
  497.  
  498.  
  499. One final point. For those with access to FAST RAM, it is possible to examine
  500. the Kickstart ROM on the Amiga 500. Simply clear the Memory Overlay Bit (OVL,
  501. bit 0, CIAAPRA) from a program in FAST RAM, and the CHIP RAM memory address
  502. range becomes mapped onto the underlying Kickstart ROM. This can be read at
  503. will. DO NOT TRY THIS FROM A PROGRAM WITHIN CHIP RAM - THE PROGRAM WILL BE
  504. LEFT HANGING AS THE 68000 PC REFERENCES THAT PART OF THE KICKSTART ROM WHICH
  505. HAS THE SAME ADDRESS AS THE NEXT INSTRUCTION IN YOUR OVL SWITCHING CODE! I
  506. HEAR THE GURU KNOCKING ALREADY...
  507.  
  508.  
  509. Hardware:DMA
  510.  
  511.  
  512. DMA (Direct Memory Access) is the technique used by most of the Amiga custom
  513. chips to perform their functions. The system is organised quite neatly, in
  514. that there are two 'halves' to the processor busses. One half is connected
  515. to all of those components accessible solely to the 68000 (such as FAST RAM
  516. if it is present) and the CIAs. The other half contains the CHIP RAM and the
  517. custom chips. The two halves are separated by a buffer, which disconnects
  518. the custom chip half from the processor whenever the processor makes an acc-
  519. ess to the FAST RAM or the CIAs. The custom chips then have total access to
  520. the CHIP RAM.
  521.  
  522.     If the processor accesses the CHIP RAM or the custom chip registers,
  523. then the buffer re-establishes the connection. In this case, there exists a
  524. risk of bus contention, where two bus controllers try to take over the busses
  525. simultaneously with obviously disastrous results. Bus accesses are nested, so
  526. that this problem is largely avoided. Also, the processor can wait until the
  527. bus is free if the blitter has absolute priority (this can be set under the
  528. control of software). Also, there exist odd and even bus cycles, and DMA acc-
  529. ess is restricted to the odd bus cycles, the even bus cycles being granted
  530. under normal circumstances to the processor.
  531.  
  532.     Right, we've got that out of the way. Now for the details. The DMA
  533. system on the Amiga consists of DMA channels, each channel assigned to one
  534. of the hardware functions. The full list of DMA channels is:
  535.  
  536.  
  537.     Bitplane DMA (6 channels): These channels are used by that part
  538.                   of the hardware which takes the bit
  539.                   plane data & converts it for output to
  540.                   the screen. If you select fewer bit
  541.                   planes, then some bitplane DMA chan-
  542.                   nels remain unused.
  543.  
  544.     Sprite DMA (8 channels)    : These channels are used by the sprite
  545.                   processor. Once a given sprite DMA
  546.                   channel has been used for generating a
  547.                   sprite, it can be re-used for another
  548.                   (with some restrictions). See later.
  549.  
  550.     Disc DMA (1 channel)    : Data transfer from disc to RAM or
  551.                   vice versa.
  552.  
  553.     Audio DMA (4 channels)    : These channels are used for processing
  554.                   of audio data in RAM & passing them to
  555.                   the sound chip. Incidentally, for any
  556.                   one interested in music, conversion of
  557.                   Amiga sound data to Fairlight synthe-
  558.                   sizer data and vice versa is possible!
  559.                   Paula's sound system possesses a limi-
  560.                   ted Fairlight compatibility.
  561.  
  562.     Copper DMA (1 channel)    : This channel is used for data transfer
  563.                   of command words to the Copper. If the
  564.                   Copperlist tells the Copper to change
  565.                   the values of registers bound to other
  566.                   DMA channels, those channels are used
  567.                   for those purposes selected within the
  568.                   Copperlist-the Copper DMA channel is
  569.                   solely for Copperlist transfer to the
  570.                   Copper.
  571.  
  572.     Blitter DMA (4 channels): These channels are used for data trans-
  573.                   fer to and from the blitter.
  574.  
  575.  
  576. Now, to make life interesting in some ways (and simpler in others) the Amiga
  577. designers related the DMA channel priorities and usages to the construction
  578. of the video picture, and the timings in bus cycles are related to the video
  579. picture mainly in order to make construction of the fabulous Amiga graphics
  580. displays easier.
  581.  
  582.     What is a bus cycle? Simply put, a time span of 280 nanoseconds. This
  583. is the time taken for a single memory access across the bus by a device using
  584. a DMA channel. Sad to say, the 68000 cannot match this speed and needs 560
  585. nanoseconds per memory access (two DMA bus cycles). The system is designed so
  586. that during these two bus cycles, access to the bus is split between the DMA
  587. channels and the 68000 as mentioned above, into odd and even cycles. Note: I
  588. haven't distinguished between read and write memory accesses for one simple
  589. reason, namely that both take the same time within this system.
  590.  
  591.     Now, if we number the cycles from zero upwards, cycle zero is given
  592. over initially to the processor. If the processor wants access to the bus, it
  593. gets it initially during cycle zero. Once cycle zero has finished, cycle one
  594. begins, which is reserved (as are all odd cycles) for the DMA controller. The
  595. DMA controller gets access to the bus during cycle one. Once cycle one has
  596. elapsed, cycle two begins and so on, access to the bus alternating between
  597. the 68000 and the DMA controller. This assumes that the 68000 wants to access
  598. the bus continuously during these cycles. If the 68000 is performing internal
  599. processing upon register data, or accessing true FAST RAM only, then that
  600. half of the bus connected to the DMA controller is available to the DMA con-
  601. troller during the even cycles as well, and should this be the case, the
  602. buffer isolates the CHIP RAM section from the 68000, and the DMA controller
  603. can access CHIP RAM during even bus cycles as well. So, in an ideal world,
  604. with a 10 meg FAST RAM expansion, your Amiga runs like the proverbial bat out
  605. of hell. Should the 68000 want to access CHIP RAM, however, then the fun be-
  606. gins, because the DMA controller is stuck with the odd cycles, except under
  607. certain conditions.
  608.  
  609.     Generally, the audio, disc and sprite DMA only use up the odd bus
  610. cycles. Thus audio, disc and sprite accesses do not slow up the processor. If
  611. large amounts of bitplane activity is required, or the blitter is activated,
  612. then some of the processor's even cycles are 'stolen' for these purposes. So
  613. when this happens, the 68000 runs more slowly.
  614.  
  615.     Ok, I said that bus cycles are related to the video picture. Well,
  616. they are. Now I'll explain how. A raster line on the screen takes 63.5 micro-
  617. seconds to produce. This is equal to 227.5 bus cycles per raster line. Each
  618. of the bus cycles that occur during this time are allocated for some purpose
  619. or other. The odd cycles are generally reserved for disc, audio and sprite
  620. DMA first, then bitplane DMA. The Copper and the blitter both use even bus
  621. cycles (tut, tut, that was naughty, Commodore!) and thus chew into the time
  622. available for the processor.
  623.  
  624.     Anyone possessing a copy of the Amiga System Programmer's Guide will
  625. no doubt have seen the little chart of DMA bus cycles for one raster line. If
  626. so, it will be noticed that the little boxes representing DMA bus cycles do
  627. not add up according to the values given along the top of each chart section.
  628. So my attempt to list in full how the DMA bus cycles are allocated here has
  629. run into trouble. Should anyone come up with a neat system of explaining this
  630. that doesn't require inclusion of an IFF picture with the DOC file as an aid
  631. please get in touch.
  632.  
  633.     Now for the start of the really useful information. The DMA control
  634. register, called DMACON, consists of two parts. There is DMACON (at offset
  635. $96) and DMACONR (at offset $02). DMACON is a write-only register, and
  636. DMACONR is a read-only register. Generally, if the register name ends in the
  637. letter 'R', it's a read-only register (nice sensible convention this). Both
  638. registers are word sized, and each bit is allocated as follows (#3,#4):
  639.  
  640.  
  641.     Bit        Function
  642.     ---        --------
  643.     15        SETIT (set or clear bits)
  644.     14        BBUSY (blitter busy-read only)
  645.     13        BZERO (blitter zero-read only)
  646.     12        Not used
  647.     11        Not used
  648.     10        BLTPRI (Blitter has absolute priority
  649.             over the 68000)
  650.      9        DMAEN (Master DMA enable)
  651.      8        BPLEN (Bitplane DMA enable)
  652.      7        COPEN (Copper DMA enable)
  653.      6        BLTEN (Blitter DMA enable)
  654.      5        SPREN (Sprite DMA enable)
  655.      4        DSKEN (Disc DMA enable)
  656.      3        AUD3EN (Enable Audio channel 3)
  657.      2        AUD2EN (Enable Audio channel 2)
  658.      1        AUD1EN (Enable Audio channel 1)
  659.      0        AUD0EN (Enable Audio channel 0)
  660.  
  661.  
  662. For bits 10 down to 0, if the bit is set, the corresponding function is
  663. enabled, else it is disabled. So to enable the blitter DMA, set bit 6 of the
  664. DMACON register.
  665.  
  666.     The DMACON register takes command words formed in a slightly odd way
  667. if you don't understand the rationale behind it. Basically, to avoid the need
  668. to read the current status, make a mask, exclusive-OR in your choice of bits
  669. to change and write back the result, in order to ensure that ONLY your choice
  670. of bits is changed, bit 15 is used to decide whether you want to set or clear
  671. the appropriate bits (hence the name, SETIT), and the other 14 bits are used
  672. to signal if each of the given bits is the bit of your choice (set if this is
  673. so, clear if not). This has the welcome effect of ensuring that DMA channels
  674. not under consideration are left alone during your write to DMACON.
  675.  
  676.     Example:to enable the bitplane DMA, bit 8 must be set. The command
  677. word thus has bit 8 set (select the bitplane DMA bit), bit 15 SET (to signal
  678. that bit 8 is to be set) and all other bits zero (leave the other DMA chan-
  679. nels unaffected). If I wished to disable the bitplane DMA, the command word
  680. I would write would have bit 8 set, bit 15 CLEAR, all others clear.
  681.  
  682.     Cross-reference #3 : the CIA chip documentation above refers to the
  683. set/clear mechanism in connection with its control registers. The above para-
  684. graphs give a complete explanation of this mechanism for anyone who has used
  685. the cross-referencing scheme to find out more. This mechanism also is used by
  686. the INTENA register (#4) and ADKCON (#5).
  687.  
  688.     As an extra safety feature, DMA channels only become truly enabled
  689. when the master DMA enable bit (bit 9) is set. So it is possible to select
  690. DMA channels one at a time, then suddenly enable the lot in one go by enab-
  691. ling the master DMA enable bit. Clearing the master DMA enable bit disables
  692. ALL DMA channels. Of course, multiple channels can be enabled, e.g.,
  693.  
  694.  
  695.         MOVE.W    #$8380,DMACON(A5)
  696.  
  697.  
  698. enables the master DMA control, the bitplane DMA, and the Copper DMA in one
  699. go (see the Preamble for notes on my choice of addressing mode and why).
  700.  
  701.     Note that the current DMA enable status can be obtained via the
  702. instruction
  703.  
  704.         MOVE.W    DMACONR(A5),D0
  705.  
  706. or something similar. A set bit indicates a DMA channel enabled.
  707.  
  708.     Incidentally, should you want to kill off AmigaDos and Exec totally
  709. (as games writers like to) then kill off all DMA using the instruction
  710.  
  711.  
  712.         MOVE.W    #$7FFF,DMACON(A5)
  713.  
  714.  
  715. in your code. This alone won't do it-you'll need to kill off the interrupts
  716. as well-but it goes a long way toward doing precisely that. The full method
  717. is :
  718.  
  719.  
  720.     1) Kill off all DMA as above;
  721.  
  722.     2) Kill off all interrupts (see below for how to do it);
  723.  
  724.     3) Point all 68000 interrupt vectors to your own custom interrupt
  725.        handlers, or RTE if you don't want to handle a given IPLx int-
  726.        errupt level;
  727.  
  728.     4) Get into supervisor mode & change the 68000 IPLx level to make
  729.        the 68000 acknowledge only those interrupts you want it to (the
  730.        4703 actually generates them-see below for how to make the 4703
  731.        generate only those interrupts that you want) using MOVE SR
  732.        (VERY NAUGHTY! SPANKING TIME FOR ALL YOU FETISHISTS OUT THERE!);
  733.  
  734.     5) Set up your own DMA system but DON'T ENABLE YET;
  735.  
  736.     6) Enable 4703 interrupts (again see below);
  737.  
  738.     7) NOW ENABLE YOUR DMA!
  739.  
  740.  
  741.     At this point Exec etc., is dead and beyond resurrection other than
  742. via a hard reset. If that's what you want, so be it.
  743.  
  744.  
  745. Hardware:Interrupts
  746.  
  747.  
  748. Ok, I've already mentioned a little about interrupts above in the DMA section
  749. but not the whole story. Now is the time to correct the omissions.
  750.  
  751.     I've already mentioned the existence of the 4703 interrupt control-
  752. ler, which actually generates the interrupts. All that the 68000 does within
  753. the Amiga is respond to these externally generated interrupts if the value of
  754. the IPLx bits allows it to. The standard value of SR on the Amiga is $0100 in
  755. user mode, $2100 in supervisor mode, and all interrupts from level 1 onwards
  756. are responded to-there's a hell of a lot of interrupts on this computer!
  757.  
  758.     The 4703 interrupt controller is programmed via two sets of custom
  759. chip registers. Again, each set has a read-only and a write-only component.
  760. These registers are:
  761.  
  762.         INTREQ  (offset $09C) : write only
  763.         INTREQR (offset $01E) : read only
  764.         INTENA  (offset $09A) : write only
  765.         INTENAR (offset $01C) : read only
  766.  
  767. INTENA is the interrupt enable register, and INTREQ is the interrupt request
  768. register. Again, the read-only ones end in 'R'. The structure of all four of
  769. these registers is identical-they are all split into individual bits, which
  770. are assigned as follows (the numbers in square brackets in the right-hand
  771. column correspoond to the 68000 IPLx priority of the said source-note that
  772. the NMI interrupt of priority 7 is never used):
  773.  
  774.  
  775.     Bit    Function
  776.     ---    --------
  777.  
  778.     15    SETIT (just like the DMACON register above)
  779.     14    INTEN (master interrupt enable)            [6] *
  780.     13    EXTER (int. from CIA-B or expansion port)    [6]
  781.     12    DSKSYN (disc sync value recognised)        [5]
  782.     11    RBF (serial receive buffer full)        [5]
  783.     10    AUD3 (output audio data channel 3)        [4]
  784.     9    AUD2 (output audio data channel 2)        [4]
  785.     8    AUD1 (output audio data channel 1)        [4]
  786.     7    AUD0 (output audio data channel 0)        [4]
  787.     6    BLIT (blitter ready)                [3]
  788.     5    VERTB (vertical blank interrupt)        [3]
  789.     4    COPER (Copper interrupt)            [3] *
  790.     3    PORTS (CIA-A or exapnsion port)            [2]
  791.     2    SOFT (reserved for software interrupts)        [2] *
  792.     1    DSKBLK (Disc DMA transfer done)            [1]
  793.     0    TBE (serial transmit buffer empty)        [1]
  794.  
  795.  
  796. Once again, if the corresponding bit from bit 13 down is set in the INTENA
  797. register, that interrupt source is enabled. If one of those bits is set by
  798. an interrupt source in the INTREQ register, the corresponding interrupt is
  799. generated & sent to the 68000. Setting or clearing the bits in INTENA/INTREQ
  800. is done in an indentical fashion to the DMACON register above. Again, the
  801. state of the master interrupt enable bit (bit 14) determines whether the 4703
  802. can generate any interrupts at all. If bit 14 is clear, NO interrupts will be
  803. generated by the 4703. Needless to say, having decided which interrupts to
  804. enable, one can enable them singly or in one go by choosing the appropriate
  805. value to write to INTENA. So, if the INTEN bit is set, and the given bit for
  806. the interrupt source is set, that interrupt CAN be generated, even if there
  807. is no guarantee that it WILL be generated.
  808.  
  809.     Ok, we can decide which interrupts to respond to. How does the 4703
  810. generate them? Simple. Any interrupt source setting a bit in the INTREQ reg-
  811. ister causes the 4703 to generate the appropriate interrupt, at which point
  812. the 68000 gets to know about it. This can either happen in hardware e.g., the
  813. blitter finishes its job & posts its interrupt signal) or can be performed in
  814. software, e.g., by setting the SOFT bit in your code directly-this will gene-
  815. rate a software interrupt signal as used by Exec for its softints, but unless
  816. Exec is alive and well, DON'T expect Exec to handle it like a softint! There
  817. is a special case, the Copper interrupt. The Copper can be made to set its
  818. own reserved Copper interrupt bit directly within a Copperlist (see later),
  819. as a means of forcing a Copper interrupt other than the vertical blank which
  820. is handled in hardware, and so is totally under your control. Those bits of
  821. INTREQ capable of being set in software by your programs at will are marked
  822. in the above list with a '*'. The others CAN be set, but care must be exer-
  823. cised if you are to do this in your code (Usually done if you are writing a
  824. set of interrupt handlers to handle the functions on a continuous basis, and
  825. HAVE to set the appropriate INTREQ bit to start the sequence off).
  826.  
  827.     So, the 68000 hears about an interrupt if:
  828.  
  829.  
  830.     1) INTEN (master interrupt enable) is set in INTENA;
  831.  
  832.     2) The corresponding interrupt source bit is set in INTENA;
  833.  
  834.     3) The corresponding interrupt source bit is also set in
  835.        INTREQ.
  836.  
  837.  
  838. All three conditions need to be fulfilled, else the 68000 will think that no
  839. interrupts are being generated by the interrupt source concerned. Further in-
  840. formation is available in the file 'typed_interrupts.doc' in this series.
  841.  
  842.     Cross-reference #4:for a full explanation of the SETIT bit, see the
  843. cross-reference #3 above.
  844.  
  845.     What do we do now? Well, you need an interrupt handler terminated by
  846. an RTE & the appropriate 68000 interrupt vector changed to point to it. If
  847. that interrupt is enabled, and its appropriate bit in INTREQ is set, then the
  848. handler will be called. Your handler should do the following:
  849.  
  850.  
  851.     1) Read INTREQR to find out which interrupt request was made. Some
  852.        of the 68000 interrupt handlers will have to handle more than
  853.        one interrupt source, and need to know which caused the inter-
  854.        rupt exception.
  855.  
  856.     2) If the bit corresponding to the interrupt source that you are
  857.        interested in is set in INTERQR , then CLEAR it in INTREQ to
  858.        signal that you've acknowledged it. The 4703 can now handle
  859.        another interrupt of the same type. Incidentally, things will
  860.        get interesting if the interrupt source posts its interrupts
  861.        faster than you can respond to them!
  862.  
  863.     3) Process your interrupt as you wish from this point on.
  864.  
  865.  
  866. This, of course, is over and above the usual things that interrupt handlers
  867. are supposed to do, such as save scratch registers on the stack & other junk
  868. that you should already be aware of. And for crying out loud, please use the
  869. MOVEM instruction to do it! Note that unlike the CIAs above, the INTREQ bits
  870. are NOT cleared when INTREQR is read! You have to clear them the hard way! I
  871. also would like to point out that setting the SETIT bit of INTREQ will cause
  872. a level 6 autovector interrupt to occur, so if you want, you can use this to
  873. create your own level 6 soft interrupts-nothing else (other than the Copper
  874. should you want it to) will set this bit but your code. Gee, isn't that nice?
  875.  
  876.     A word of warning:on my machine at least (this may vary), something
  877. quaint happens if one tries performing the instruction
  878.  
  879.  
  880.         CLR.W    INTREQ(A5)
  881.  
  882.  
  883. or similar, due to the read/write access of the 68000 CLR instruction (see
  884. the Preamble). The machine seems to 'hiccup' before carrying on as normal. I
  885. would not suggest doing this too often, it might blow something expensive to
  886. mend. In any case, the above instruction does bugger all to the status of the
  887. interrupt system for reasons made obvious upon analysis (see #3 above), so I
  888. don't think that there's much point in doing it-I only did it by accident. I
  889. cannot stress too much, however, that the Preamble caveat about CLR should be
  890. adhered to (I only found out after extensive use of CLR in my code & had to
  891. rip it all apart again to make it work properly. Some unfortunates have some
  892. copies of my old code instead of the CLR-free versions & wonder what the hell
  893. is going on when they run it...).
  894.  
  895.  
  896. Hardware:The Copper
  897.  
  898.  
  899. This is one of the harder chapters to write, and for a very good reason. The
  900. Copper is a very powerful little piece of hardware, but with that power comes
  901. complexity.
  902.  
  903.     The Copper is a coprocessor capable of writing values to the custom
  904. chip registers independently of the 68000, and of performing actions based on
  905. the position of the video beam. All in all, a highly useful little fellow. As
  906. befits what is a processor in its own right, it has its own machine language
  907. and it is programs written in this special Copper machine language that are
  908. the famous Copperlists of Amiga parlance. At this point, those thinking to
  909. themselves 'oh, no, not another machine language to learn!' should be reas-
  910. sured by the knowledge that there are only three basic instruction types in
  911. Copper machine language. These three basic instruction types are versatile,
  912. however, and much can be done with them.
  913.  
  914.     Sad to say, Copperlists have to be created by hand as far as I am
  915. aware, at least if you want to take advantage of ALL Copperlist features.
  916. I have been told that the Argasm assembler can take Copperlists in the form
  917. of Copper assembly language & assemble them, but I've yet to check this. And
  918. yes, there is a Copper assembly language to make life a little easier when
  919. creating Copperlists.
  920.  
  921.     So, to the Copper Assembly Language (CAL for short). The three basic
  922. CAL instructions are:
  923.  
  924.  
  925.     MOVE    : Write an immediate data value into a custom chip
  926.           register (like the 68000 MOVE #nnnn,xxxx);
  927.  
  928.     WAIT    : Wait until the electron beam generating the video
  929.           picture has reached a certain position;
  930.  
  931.     SKIP    : If the electron beam has reached the specified
  932.           position, skip the next CAL instruction, else
  933.           execute sequentially as normal.
  934.  
  935.  
  936. Doesn't seem much, does it? Well, you can do a hell of a lot with this to
  937. hand. I shall deal with the instructions in turn.
  938.  
  939.     The MOVE instruction:this instruction allows the Copper to write an
  940. immediate value into a custom-chip register. The register is specified in the
  941. instruction as an offset from the base address $DFF000 (now see why I prefer
  942. using offset(An) in 68000 for addressing custom chip registers. The Copper
  943. does it in hardware! Makes for consistency in programming) and the value to
  944. write is always a WORD value. The CAL syntax is
  945.  
  946.  
  947.         MOVE    #value,register
  948.  
  949.  
  950. for anyone blessed with a CAL assembler (or Argasm if it does this for you).
  951. The actual way that the instruction is coded as machine words in memory is:
  952.  
  953.  
  954.         %0000000rrrrrrrr0,$XXXX
  955.  
  956.  
  957. Here, rrrrrrrr represents the register address. Since all register offsets
  958. from $DFF000 are even, bit 0 of the first word of a MOVE instruction is al-
  959. ways zero. The second word contains the 16-bit value to write to the chosen
  960. custom-chip register. For example, to write the value corresponding to the
  961. colour light green into palette register 3, one would use the CAL syntax
  962.  
  963.  
  964.         MOVE    #$03C3,COLOR03
  965.  
  966.  
  967. which would become (since COLOR03 is at offset $186) the machine words
  968.  
  969.  
  970.         $0186,$03C3
  971.  
  972.  
  973. This seems simple enough. Now, the fun starts. There is a restriction upon
  974. the registers that can be written to by the Copper. Under normal circumstan-
  975. ces, the Copper cannot write to registers from offsets $000 to $07E (most of
  976. these are read-only anyway). There exists a special custom chip register, the
  977. COPCON register, consisting of one bit (bit 0). If this bit, which is called
  978. the Copper Danger Bit or CDANG bit, is set, then the Copper can access the
  979. custom chip registers from offsets $040 to $07E, which just happen to be the
  980. blitter control registers. Access to the registers from offsets $000 to $03E
  981. is NEVER allowed. COPCON itself is at $02E (write-only) and inaccessible to
  982. the Copper itself (the 68000 must write to this register).
  983.  
  984.     So, bearing this restriction in mind, the Copper can write to most
  985. of the custom chip registers, and if allowed to by the 68000, can write to
  986. the blitter control registers and influence the blitter. This alone gives the
  987. Copper considerable power within the system. In particular, the Copper can
  988. change the DMA enable status, the interrupt enable status, the sprite control
  989. registers, the palette, the bitplane control, the sound chip, and to a limit-
  990. ed extent, the disc controller! Needless to say, it's only safe to let the
  991. Copper do all this when you know how it's all done. See each section in turn
  992. for the requisite information.
  993.  
  994.     The WAIT instruction:this instruction causes the Copper to do just
  995. that, wait. The Copper waits for a specific position to be reached by the
  996. electron beam generating the video picture before continuing execution of
  997. the remaining instructions in the Copperlist. This is how various tricks are
  998. achieved such as changing background colours at specified screen positions
  999. to create 'sunset' effects etc. The Copperlist contains a sequence of WAITs
  1000. interspersed with MOVEs to the background colour palette register, COLOR00 at
  1001. offset $180. Should the electron beam have already passed the given position,
  1002. normal sequential execution is resumed. The CAL syntax for WAIT is
  1003.  
  1004.  
  1005.         WAIT    (x1,y1) MASK (x2,y2) BFD
  1006.  
  1007.  
  1008. (Anyone used to the CMOVE/CWAIT macros on Devpac here forget those-they never
  1009. use the full power of the WAIT instruction. This is MY defined CAL syntax for
  1010. the WAIT instruction, that tells you everything).
  1011.  
  1012.     In this syntax, x1 and y1 are the beam position to wait for. In this
  1013. syntax, the MASK and BFD entries are optional and can be omitted, but if they
  1014. are included have a profound effect. More of this below. If omitted, the WAIT
  1015. instruction makes the Copper wait until the beam reaches position (x1,y1) and
  1016. then resume normal sequential execution.
  1017.  
  1018.     If the MASK specifier is included, the fun starts. Instead of using
  1019. (x1,y1) directly, the comparison of the beam position is made with the values
  1020. formed by logically ANDing together x1 and x2 for the horizontal position, &
  1021. ANDing together y1 and y2 for the vertical position. Omitting the MASK speci-
  1022. fier is to be regarded as having the same effect as having a MASK value of
  1023. (-1,-1), or all 1's in binary (in which case x1 AND x2 becomes x1, etc.).
  1024.  
  1025.     This opens up many possibilities. For example, in the instruction
  1026.  
  1027.  
  1028.         WAIT    (0,$0F) MASK (-1,$0F)
  1029.  
  1030.  
  1031. the WAIT condition will be fulfilled every 16 lines, i.e., whenever the lower
  1032. four bits of y1 are all 1. Note the -1 mask value for the horizontal position
  1033. (i.e., all 1's binary). Since in this example I am not interested in the hor-
  1034. izontal position at all, I could have had a horizontal mask of 0, but if the
  1035. horizontal position is important, choose the mask accordingly. The mask bits
  1036. affect BOTH the specified position in the instruction AND the actual beam
  1037. position coordinates before the position comparison is performed.
  1038.  
  1039.     The machine words for the WAIT instruction take the form:
  1040.  
  1041.  
  1042.         %vvvvvvvvhhhhhhhh1,%bvvvvvvvhhhhhhh0
  1043.  
  1044.  
  1045. In the first word, the vvv bits specify the vertical beam position, and the
  1046. hhh bits the horizontal beam position. Note that bit 0 is equal to 1. This
  1047. distinguishes WAIT (and SKIP below) from MOVE. WAIT is distinguished from
  1048. SKIP by having bit 0 of the second machine word set to zero (for SKIP, this
  1049. is set to 1).
  1050.  
  1051.     In the second word, the b bit is the Blitter Finish Disable bit, or
  1052. BFD bit. In my CAL syntax, including BFD in the instruction specification has
  1053. the meaning 'set the BFD bit in the second word'. This bit is used when the
  1054. Copper is used to start a blitter operation. The Copper in general must know
  1055. when the blitter has finished whatever blitter operation was started at some
  1056. time past, whether started by the Copper or the 68000. If the BFD bit is zero
  1057. (omitting BFD in the CAL syntax means 'clear the BFD bit') then the Copper
  1058. will WAIT until the blitter finishes, and THEN check the wait condition. If
  1059. the BFD bit is one, the blitter status is ignored. If COPCON=0, and the
  1060. Copper does not affect the blitter in any way, BFD should be set to 1.
  1061.  
  1062.     In the second word, the vvv bits are the vertical mask, and the hhh
  1063. bits the horizontal mask. If no mask is specified, these are all set to 1.
  1064. Note that bit 7 of the vertical position cannot be masked. If a vertical mask
  1065. is specified, then bit 7 of the vertical position is always treated as though
  1066. the mask bit for that position was 1. Note that since there are 313 lines of
  1067. display, and the vertical position is only 8 bits wide (and the vertical mask
  1068. 7 bits wide), that WAITs for vertical positions greater than 255 have to be
  1069. performed as
  1070.  
  1071.  
  1072.         WAIT    (0,255)
  1073.         WAIT    (0,y)
  1074.  
  1075.  
  1076. NOTE : Horizontal positions are specified in steps of 4 low-resolution pixels
  1077. and NOT in pixel coordinates directly!
  1078.  
  1079.     The SKIP instruction:the only difference between this instruction &
  1080. the WAIT instruction in terms of machine words is that bit 0 of the second
  1081. word is 1 instead of 0. The bits are otherwise identical in format to those
  1082. for the WAIT instruction.
  1083.  
  1084.     The SKIP instruction allows conditional branches to be set up within
  1085. a Copperlist. The mechanism is slightly quirky, however. Basically, the beam
  1086. position is compared with the (x1,y1) arguments as for the WAIT instruction,
  1087. with MASK data also applying identically. If the beam position is greater
  1088. than or equal to the (x1,y1) argument (MASK notwithstanding) then the Copper
  1089. skips the next Copperlist instruction, and moves on directly to the instruc-
  1090. tion following it. Otherwise, instruction execution continues in the normal
  1091. sequential fashion. Full information on conditional branches using this in-
  1092. struction is given below. As may be expected, my CAL syntax for the SKIP in-
  1093. struction is
  1094.  
  1095.  
  1096.         SKIP    (x1,y1) MASK (x2,y2) BFD
  1097.  
  1098.  
  1099. just as for the WAIT instruction. Comments regarding the optional MASK and
  1100. BFD arguments applying to WAIT apply identically to SKIP.
  1101.  
  1102.     Now, we have the three Copper instructions. A Copperlist is simply
  1103. a sequential list of these instructions, in machine word format, in memory.
  1104. As may be expected, the Copperlist MUST be in CHIP RAM.
  1105.  
  1106.     Having read this far, one may wonder about how a Copperlist is ter-
  1107. minated. A trick is used here. The final instruction in a Copperlist is a
  1108. WAIT instruction for an impossible beam position, such as WAIT (0,$FE). This
  1109. condition will never be fulfilled because a horizontal beam position greater
  1110. than $E4 isn't possible. I personally use the machine words
  1111.  
  1112.  
  1113.         DC.W    $FFFF,$FFFE
  1114.  
  1115.  
  1116. as the end of my Copperlist. When the beam reaches the end of the video pic-
  1117. ture, the Copper is automatically restarted at the start of the Copperlist
  1118. (unless you arrange otherwise!).
  1119.  
  1120.     Ok. We have a Copperlist, complete with the impossible WAIT at the
  1121. end. How do we tell the Copper to execute our Copperlist? The Copper has a
  1122. set of registers for this. These are:
  1123.  
  1124.  
  1125.     COP1LCH        offset $080
  1126.     COP1LCL        offset $082
  1127.     COP2LCH        offset $084
  1128.     COP2LCL        offset $086
  1129.     COPJMP1        offset $088
  1130.     COPJMP2        offset $08A
  1131.  
  1132.  
  1133. The two register pairs, COP1LCH/L and COP2LCH/L, are loaded with the 18-bit
  1134. CHIP RAM address of the start of your Copperlist (or some other address-see
  1135. later!). For simple Copperlists, COP1LCH/L alone is used. Having done this,
  1136. and turned on the Copper DMA, writing any value to COPJMP1 starts the Copper
  1137. executing your Copperlist. When the Copper reaches the impossible WAIT ins-
  1138. truction at the end of your Copperlist, it will WAIT until the vertical blank
  1139. occurs, at which point the Copper will restart at the address loaded into the
  1140. COP1LCH/L pair. More correctly, COPJMP1 causes the data in the COP1LCH/L pair
  1141. to be transferred to the Copper's internal program counter, and execution in-
  1142. itiated. If you have an address in COP2LCH/L, writing to COPJMP2 will cause
  1143. that value to be loaded instead. For simple Copperlists (no interlace or any
  1144. conditional branches) the COP1LCH/L and COPJMP1 set are the defaults used, &
  1145. these will be used by the Copper for restarting the Copperlist execution at
  1146. the vertical blank interval. NOTE:the Copper needs its 'programs' aligned on
  1147. a word boundary just like the 68000. In fact, word alignment holds for all
  1148. custom chip operations - unless I discover any exceptions and document them
  1149. in this file, treat word alignment as mandatory.
  1150.  
  1151.     Note that the COPxLCH/L register pairs are NOT program counters! The
  1152. Copper's program counter is NOT directly accessible, and the values stored in
  1153. the COPxLCH/L register pairs are INITIAL program counter values, needing to
  1154. be loaded only once under normal circumstances. The values in COPxLCH/L never
  1155. change once loaded, unless 1) they are changed by the 68000 at some future
  1156. time (under your control!); 2) the Copperlist contains instructions such as
  1157.  
  1158.  
  1159.         MOVE    #value_hi,COP1LCH    ;high word of 18-bit value
  1160.         MOVE    #value_lo,COP1LCL    ;low word of same
  1161.  
  1162.  
  1163. which causes the Copper to alter them itself.
  1164.  
  1165.     Conditional Branches:now it may already have become obvious to the
  1166. astute reader how to form a conditional branch in CAL. For those who haven't
  1167. yet worked out all of the details, here they are.
  1168.  
  1169.     First, one needs to know the absolute address in memory of the point
  1170. to which to branch. BEFORE the branch is to be executed, reload COP1LCH/L
  1171. with this new address-the Copper can be made to do it using instructions such
  1172. as the example above. Then immediately after a SKIP instruction, place the
  1173. Copper instruction
  1174.  
  1175.  
  1176.         MOVE    #0,COPJMP1
  1177.  
  1178.  
  1179. and the rest of the Copperlist following this. If the beam position when the
  1180. Copper reaches the SKIP instruction is greater than the SKIP instruction's
  1181. position argument, the MOVE above will be skipped, and the remaining inst-
  1182. ructions of the Copperlist following the MOVE executed. If the position is
  1183. less than the argument, the MOVE above will be executed, and the Copper will
  1184. load its internal program counter with the new value of COP1LCH/L that you
  1185. forced it to earlier on. Hey presto! Conditional branch! Of course, if you
  1186. wish to leave COP1LCH/L alone, you can use COP2LCH/L instead, and use a MOVE
  1187. to COPJMP2 to cause the branch instead.
  1188.  
  1189.     WARNING:If you change COP1LCH/L in order to force a conditional br-
  1190. anch using the above mechanism, REMEMBER TO RESET IT TO POINT TO THE START OF
  1191. YOUR COPPERLIST AGAIN AFTER THE BRANCH! You have to do this in two places in
  1192. your Copperlist, once after the MOVE to COPJMP1 (to take account of branch
  1193. not performed) and once immediately after the branch point (to take account
  1194. of branch performed). Failure to do this will result in the Copper failing
  1195. to execute portions of your Copperlist after the first execution!
  1196.  
  1197.     Interlaced playfields:you need two Copper lists for this, one for
  1198. the long frame and one for the short frame. The long frame Copperlist (the
  1199. first one) should initialise bitplane pointers to point to the FIRST line of
  1200. the bitplanes, and the short frame Copperlist should initialise the bitplane
  1201. pointers to point to the SECOND line of the bitplanes. At the end of the long
  1202. frame Copperlist, before the impossible WAIT, insert two instructions to set
  1203. the COP1LCH/L pair to point to the short frame Copperlist. Similarly, at the
  1204. end of the short frame Copperlist, place instructions to point COP1LCH/L at
  1205. the start of the long frame Copperlist. The Copper will then alternate back
  1206. and forth between the two Copperlists. In addition, the bitplane control (see
  1207. below) needs to have the LACE bit set, and various other instructions need to
  1208. be executed to ensure proper system synchronisation, and ensure that your in-
  1209. terlaced playfields are displayed properly. More details in the section below
  1210. on bitplane control.
  1211.  
  1212.     Note:incorrect setting of the Copper registers can lead to the so-
  1213. called FIREWORKS_MODE of the Amiga occurring. This occurs when the Copper is
  1214. pointed to an invalid area of memory, and the Copper tries to execute what it
  1215. thinks is a Copperlist there. The Copper isn't intelligent (like some COBOL
  1216. programmers I know) and thinks that anywhere it's pointed to is a Copperlist
  1217. to execute, and happily runs it. This usually has weird and wonderful effects
  1218. such as screwing up the screen completely. This phenomenon (the runaway Cop-
  1219. per syndrome) is the ONE event that can crash the Amiga completely, beyond
  1220. even a Guru recovery. It's sometimes pretty to watch, but can result in your
  1221. Amiga containing a fried Agnus or something else fatal if you don't switch
  1222. off the moment it happens. YOU HAVE BEEN WARNED.
  1223.  
  1224.     Copper interrupt:In the section on interrupt control, it was stated
  1225. that the Copper has its own interrupt control bit in INTENA/INTREQ. To signal
  1226. a Copper interrupt, place the instruction
  1227.  
  1228.  
  1229.         MOVE    #$8010,INTREQ
  1230.  
  1231.  
  1232. into your Copperlist at the desired point, and the Copper will force the int-
  1233. errupt system to generate the Copper interrupt. Any interrupt bit can be set
  1234. this way, but the above instruction sets bit 4 of INTREQ, specially provided
  1235. for the Copper. By placing this instruction after suitable WAIT instructions
  1236. one can tell the 68000 that a given screen position has been reached, and is
  1237. the recommended method of setting up Raster Interrupts. Amiga Raster Inter-
  1238. rupts are completely controllable, and can be made to occur not only at a
  1239. given raster line position, but at a given screen column as well! Using the
  1240. MASK option in WAIT allows all manner of wonderful tricks to be performed.
  1241. The only limit is your imagination at this point.
  1242.  
  1243.  
  1244. Hardware:Bitplanes & Bitplane Control
  1245.  
  1246.  
  1247. Having discovered how to generate a Copperlist, the next logical step is to
  1248. learn how to control the bitplane usage. All bitplane control registers are
  1249. accessible to the Copper (except for those below offset $040), and thus one
  1250. can set up a Copperlist to set these registers to given values. This is of
  1251. particular value for interlaced playfields, already mentioned in the Copper
  1252. section above, but can be performed for any type of playfield if wanted.
  1253.  
  1254.  
  1255.     Bitplane Control Registers:the full list of bitplane control regis-
  1256. ters is:
  1257.  
  1258.  
  1259.     VPOSR    (offset $004)    Read MSB of vertical beam position
  1260.     VHPOSR    (offset $006)    Read vertical/horizontal beam position
  1261.  
  1262.     VPOSW    (offset $02A)    Write MSB of vertical beam position
  1263.     VHPOSW    (offset $02C)    Write vertical/horizontal beam pos
  1264.  
  1265.     DIWSTART    (offset $08E)    set top left corner of display window
  1266.     DIWSTOP    (offset $090)    set bottom right corner of same
  1267.     DDFSTART    (offset $902)    horiz. pos start of bitplane DMA fetch
  1268.     DDFSTOP    (offset $094)    horiz. pos end of bitplane DMA fetch
  1269.  
  1270.     BPL1PTH    (offset $0E0)    bitplane pointers, high/low, for
  1271.     BPL1PTL    (offset $0E2)    up to 6 bitplanes as wanted
  1272.     BPL2PTH    (offset $0E4)
  1273.     BPL2PTL    (offset $0E6)
  1274.     BPL3PTH    (offset $0E8)
  1275.     BPL3PTL    (offset $0EA)
  1276.     BPL4PTH    (offset $0EC)
  1277.     BPL4PTL    (offset $0EE)
  1278.     BPL5PTH    (offset $0F0)
  1279.     BPL5PTL    (offset $0F2)
  1280.     BPL6PTH    (offset $0F4)
  1281.     BPL6PTL    (offset $0F6)
  1282.  
  1283.     BPLCON0    (offset $100)    main bitplane control register
  1284.     BPLCON1    (offset $102)    scroll values for outsize playfields
  1285.     BPLCON2    (offset $104)    sprite/playfield & DUALPF control
  1286.  
  1287.     BPL1MOD    (offset $108)    bitplane modulo for odd planes
  1288.     BPL2MOD    (offset $10A)    bitplane modulo for even planes
  1289.  
  1290.  
  1291. The main bitplane control register BPLCON0 is organised as follows (bit set
  1292. equals function enabled,  bit clear equals function disabled):
  1293.  
  1294.  
  1295.     Bit    Function
  1296.     ---    --------
  1297.     15    HIRES        Turn on high-resolution mode
  1298.     14    BPU2        These three bits contain the
  1299.     13    BPU1        number of bitplanes used
  1300.     12    BPU0
  1301.     11    HOMOD        Hold & Modify mode on
  1302.     10    DBPLF        Dual Playfield mode on
  1303.      9    COLOR        Video output colour (always set this!)
  1304.      8    GAUD        Genlock Audio on
  1305.     7-4    Unused
  1306.      3    LPEN        Lightpen input active
  1307.      2    LACE        Interlace mode on
  1308.      1    ERSY        External synchronisation on
  1309.      0    Unused
  1310.  
  1311.  
  1312. Some restrictions exist. HOMOD and DBPLF cannot both be set simultaneously,
  1313. one or the other only can be set. Both bits can be cleared, however, and if
  1314. all six bitplanes are enabled, the hardware automatically selects the EXTRA-
  1315. HALFBRITE mode. Also, GAUD and ERSY are only useful with a Genlock interface
  1316. (DO NOT SET THEM UNLESS YOU'RE USING ONE!). The legal value range for the
  1317. BPUx bits is 0 to 6, 7 is not allowed. Don't ask me why 0 is allowed...
  1318.  
  1319.     Having decided which screen mode is desired, one then needs to set
  1320. the bitplane sizes. The registers DIWSTART (Display Window Start) and DIWSTOP
  1321. (Display Window Stop) are used for this. Bits 15-8 contain the vertical pos-
  1322. ition, and bits 7-0 the horizontal position.
  1323.  
  1324.     DIWSTART is assumed to rest in the top left quadrant of the screen.
  1325. This is a fairly sensible assumption, after all. Because the vertical pos-
  1326. ition can be from 0 to 313, which needs 9 bits, the top bit (not specified)
  1327. is assumed to be zero, giving vertical positions from 0 to 255. Similarly,
  1328. the missing 8th bit of the horizontal position is assumed to be 0, giving a
  1329. horizontal position from 0 to 255.
  1330.  
  1331.     DIWSTOP is a little more complicated. It is assumed to lie in the
  1332. lower right quadrant of the screen (sensible again) and hence the 9th bit
  1333. of the horizontal position is assumed to be 1, giving horizontal positions
  1334. from 256 to 448. Because vertical end positions both greater than and less
  1335. than 255 should be possible, a trick is used. Bit 15 (the 7th bit of the
  1336. vertical position) of DIWSTOP is inverted to provide the 8th bit, making an
  1337. end position of 128 to 312 possible. For end positions from 256 to 312, make
  1338. this bit zero (thus making the hidden 8th bit equal to 1), and for end posi-
  1339. tions from 128 to 255, make this bit 1 (thus making the hidden 8th bit 0).
  1340. Also, DIWSTOP should have the horizontal and vertical values PLUS ONE set
  1341. into it to work properly.
  1342.  
  1343.     Typical PAL values for the screen are TLC (top left corner) coord-
  1344. inates (129,41), and BRC (bottom right corner) coordinates (448,296). This
  1345. corresponds to DIWSTART = $2981, and since DIWSTOP should contain the values
  1346. (449,297) instead of (448,296), DIWSTOP = $29C1 is used. This produces a PAL
  1347. 320 x 256 display area centred in the middle of the monitor display.
  1348.  
  1349.     Limitations exist on these values. Firstly, monitor tube distortions
  1350. limit the values (the corners will be cut off if the entire monitor screen
  1351. area is used), and the blanking gaps need to be taken into account. Vertical
  1352. blanking gaps occupy lines 0 to 25, making the earliest TLC vertical position
  1353. 26 lines from the VBL start, and the latest BRC vertical position is 312. The
  1354. horizontal situation is more complex. The horizontal blanking gap (HBL) lies
  1355. between colums 30 and 106. Horizontal positions from 107 are possible.
  1356.  
  1357.     We have set the screen mode, and the bitplane size. Now we need to
  1358. set up the bitplane DMA. The DMA data fetch must start in synchronisation
  1359. with the start & stop values, to ensure that the pixels appear in the right
  1360. places on screen. Vertically, this is no problem. Screen DMA starts and ends
  1361. in synchronisation with the DIWSTART/DIWSTOP vertical positions automatically
  1362. and no register control of this is provided. Horizontally, this is a problem
  1363. however. To display a pixel on the screen, the current word needs to be read
  1364. from each bitplane. for 6 bitplanes, low-resolution, 8 bus cycles are needed.
  1365. In addition, the hardware needs a half bus cycle before the data can appear
  1366. on the screen. The bitplane DMA must therefore start exactly 8.5 cycles or
  1367. 17 pixels before the start of the screen window for low-resolution screens,
  1368. and 4.5 cycles or 9 pixels before the start of the screen window for high-
  1369. resolution screens.
  1370.  
  1371.     The registers controlling this data fetch are DDFSTART and DDFSTOP
  1372. (Display Data Fetch Start, and Display Data fetch Stop). Only bits 7 to 2
  1373. are writeable, the others are "don't care" bits and should be set to 0. Bit
  1374. 2, the lowest writeable bit, should always be 0 for low-resolution screens
  1375. since the bitplanes are read once every 8 bus cycles, and the values of
  1376. both DDFSTART and DDFSTOP must be an exact multiple of 8. Regardless of the
  1377. resolution, the difference between DDFSTART and DDFSTOP (the Amiga System
  1378. Programmer's Guide is littered with misprints about here!) must always be
  1379. divisible by 8, since the hardware always divides the lines into sections
  1380. of 8 bus cycles each. Even in high-res mode, the bitplane DMA is performed
  1381. for 8 bus cycles beyond DDFSTOP, so that 32 points are always read.
  1382.  
  1383.     Let H equal the horizontal start of the screen, as set in DIWSTART.
  1384. Also, let P equal the number of pixels per line. The values for DDFSTART and
  1385. DDFSTOP are thus computed as:
  1386.  
  1387.     Low Resolution    : DDFSTART = (H/2 - 8.5) AND $FFF8
  1388.  
  1389.               DDFSTOP  = DDFSTART + P/2 - 8
  1390.  
  1391.  
  1392.     High resolution    : DDFSTART = (H/2 - 4.5) AND $FFF8
  1393.  
  1394.               DDFSTOP  = DDFSTART + P/4 - 8
  1395.  
  1396.  
  1397. For our standard PAL window of 320x256 centred as above, we have H=129, P=320
  1398. and the values are thus
  1399.  
  1400.  
  1401.     DDFSTART : (129/2 - 8.5) AND $FFF8 = $38
  1402.  
  1403.     DDFSTOP  : $38 + 320/2 - 8 = $D0
  1404.  
  1405.  
  1406. For a high-resolution screen of 640x256 centred as above, we now have H=129,
  1407. P=640, and the values are thus
  1408.  
  1409.  
  1410.     DDFSTART : (129/2 - 4.5) AND $FFF8 = $3C
  1411.  
  1412.     DDFSTOP  : $3C + 640/4 - 8 = $D4
  1413.  
  1414.  
  1415. DDFSTART cannot be less than $18. This is because the first $18 bus cycles
  1416. are reserved for the memory refresh, disc and audio DMA, and the DMA channel
  1417. for sprite 0 (used as the mouse pointer) which cannot be turned off. DDFSTOP
  1418. is limited to a maximum of $D8 (horizontal blank occurs beyond this!).
  1419.  
  1420.     Bitplane Pointers:the list above of registers includes the bitplane
  1421. pointers BPLxPTH/L. Each word-sized 'L' register combines with its 'H' coun-
  1422. terpart to form a pointer into the CHIP RAM. By setting these pointers to the
  1423. address of the start of each portion of bitplane memory, and then setting the
  1424. BPLCON0 register for the appropriate screen mode, bitplane control is almost
  1425. complete.
  1426.  
  1427.     Note that in this case, the bitplane pointer contents are CHANGED by
  1428. the operation of the system, as opposed to the COPxLCH/L registers above. As
  1429. a result, the bitplane pointers need to be reset after each use, either by an
  1430. appropriate Copperlist, or by the 68000 during the VBL. There exist six other
  1431. registers called BPLxDAT which are accessible only by the DMA system. When a
  1432. BPLxPTH/L register pair is accessed to obtain a bitplane address, it is inc-
  1433. remented by two after the requisite data word is accessed and passed on to
  1434. the BPLxDAT register. Once the full complement of BPLxDAT registers for the
  1435. given screen are loaded, their data is passed to the display electronics, and
  1436. the process repeated. Either at the VBL or within the Copperlist, each of the
  1437. BPLxPTH/L registers need to be reset as a result. The actual reading of the
  1438. bitplane data occurs during the interval between the occurrence of DDFSTART &
  1439. DDFSTOP. After DDFSTOP has been reached, the bitplane pointers are changed by
  1440. the values contained in the BPLxMOD registers, and under normal circumstances
  1441. these registers are set to zero. The BPLxMOD registers will be covered more
  1442. fully later on in this section.
  1443.  
  1444.     So far, this information assumes that the playfields are designed to
  1445. be the same size as the area displayed. It is perfectly possible to design a
  1446. collection of outsize playfields larger than the display area, and display a
  1447. portion of each. The playfield can be extra-tall, extra-wide or both, making
  1448. screen scrolling almost ridiculously easy in comparison with other computers
  1449. such as the Atari ST.
  1450.  
  1451.     To manage extra-tall playfields is simplicity itself. Simply alter
  1452. the values of BPLxPTH/L used as the start point for vertical scrolling. If
  1453. this cannot be done in a Copperlist, use the 68000 during the VBL. One way
  1454. of making the Copperlist handle it is to write to the Copperlist directly,
  1455. using the Copper interrupt to signal that the Copper has executed beyond the
  1456. point at which you wish to write the new addresses into the Copperlist, and
  1457. performing the write operation during the Copper interrupt. Alternatively one
  1458. can use the 68000 during the VBL interrupt, storing the true base pointers
  1459. and the scrolled values somewhere safe beforehand, and updating the scrolled
  1460. values each time a scroll is performed.
  1461.  
  1462.     Note that I mention using the Copper interrupt to signal that it is
  1463. safe to write into the Copperlist. If this is not done, it is possible to
  1464. write into the Copperlist at the same point being accessed by the Copper, and
  1465. thus ensuring that the Copper gets the wrong data. Use of the Copper inter-
  1466. rupt ensures that the Copper has genuinely finished with the portion of the
  1467. Copperlist being rewritten.
  1468.  
  1469.     Managing extra-wide playfields is a little more complicated, but the
  1470. hardware makes for almost unbelievable speed in pixel-boundary horizontal
  1471. scrolling. BPLCON2 is used to control the pixel offset from 0-15 (remember,
  1472. the DMA system accesses bitplanes in 16-bit words, corresponding to 16 pixels
  1473. of bitplane data). Bits 15-8 of BPLCON2 are unused. Bits 7-4 are used to con-
  1474. trol the pixel offset for the odd planes, and bits 3-0 are used to control
  1475. the pixel offset for the even planes. BPLCON2 determines the number of pixels
  1476. to the LEFT that the screen is scrolled, so for scrolling to the RIGHT, one
  1477. must use 16-X (where X is the left scroll value) and add 2 to each of the
  1478. bitplane pointers.
  1479.  
  1480.     Also, to ensure that the extra-wide playfield is properly displayed,
  1481. there exist modulo registers. Modulo registers are used extensively within
  1482. the Amiga hardware, particularly by the blitter. A modulo register contains a
  1483. value to be added on to a pointer register pair value in order to ensure that
  1484. the pointer points to the correct data word after a series of operations. An
  1485. example will illustrate.
  1486.  
  1487.     Let us create a 640-pixel low-resolution display. This is twice as
  1488. wide as the standard display of 320 pixels. After reading the first 20 words
  1489. of the display (40 bytes), the bitplane pointers are pointing to word 21. In
  1490. a normal display, the BPLxMOD registers contain zero, and this is added on to
  1491. the BPLxPTH/L values to reference the next line. For our double-width play-
  1492. field, this is not correct. We want to skip another 20 words (40 bytes) to
  1493. reference the second line correctly. This is done by setting BPLxMOD to 40.
  1494. This is then added on to the BPLxPTH/L pairs by the system and the second
  1495. line of our double-width playfield is thus referenced correctly by the DMA
  1496. system.
  1497.  
  1498.     Of course, both can be combined to make a huge display area, the
  1499. sole limitations being available CHIP memory and your imagination. This can
  1500. then be scrolled around at will.
  1501.  
  1502.     Note that for smooth scrolling, the scroll values MUST be changed
  1503. outside the time used for displaying the actual bitplanes. This again is
  1504. possible using the Copper or the VBL interrupt as above.
  1505.  
  1506.     Basically, scrolling smoothly is achieved by keeping a pixel scroll
  1507. value saved somewhere as well as the bitplane pointers. To scroll left, take
  1508. the pixel scroll value, add 1, AND with $0F and save back. If the result is
  1509. zero, add 2 to all bitplane pointers. Then write these values into the vari-
  1510. ous BPLCON2/BPLxPTH/L registers. For smooth right scrolling, take the pixel
  1511. scroll value, subtract 1, AND with $0F, save back. If the result equals $0F
  1512. then subtract 2 from all bitplane pointers. Write all of the resulting data
  1513. into the requisite registers. So now you know.
  1514.  
  1515.     Double-Buffering:at this point, any reader having digested both of
  1516. the sections on Copperlists and Bitplane Control will have all the informa-
  1517. tion to hand to perform double-buffering in hardware. Set up a Copperlist for
  1518. the desired screen, complete with bitplane pointer initialisation. I find it
  1519. useful to refer to the screen within which rendering is performed as the
  1520. logical screen, and the screen currently being displayed as the physical
  1521. screen. The double-buffering technique keeps these screens separate. Set up
  1522. the Copperlist initially to point to one of the screens, which will become
  1523. the physical screen. Perform all rendering in the other screen, which will
  1524. become the logical screen, and use the Copper interrupt to determine when it
  1525. is safe to change the bitplane pointer initialisation section to restart the
  1526. Copperlist after the VBL with the identities of the two screens changed. The
  1527. previous logical screen, within which one has rendered all graphic data, will
  1528. become the new physical screen, and the current physical screen will then be-
  1529. come the new logical screen. Again, perform all rendering in the logical scr-
  1530. een. Provided that all rendering can be performed within the time taken to
  1531. display one frame (1/50th of a second), the resulting motions of graphic en-
  1532. tities within your program will be completely smooth and flicker-free. This
  1533. technique requires two sets of screen memory and is thus memory-hungry, but
  1534. it is the basic technique for most games requiring smooth object motions. I
  1535. shall add at this point that it may be possible to achieve smooth motion by
  1536. this means even if it takes up to three frames to perform all rendering, as
  1537. the movement of objects within 'Strike Force Harrier' on the ST is reason-
  1538. ably smooth (I once worked for the author of that game) even though frame
  1539. swapping only occurs at 16 frames per second. With the Amiga's far superior
  1540. hardware is should be possible to perform similar rendering at 24 frames per
  1541. second or even faster (Strike Force Harrier has up to 32 bob-type objects on
  1542. screen at once, hence the time taken for rendering!), and 50 frames per sec-
  1543. ond animation is perfectly possible with fewer objects to move, unless they
  1544. are truly huge (but see 'Menace'-some of that program's bobs are of a vast
  1545. size). With dual playfield mode and oversize playfields, it's even possible
  1546. to perform fast rendering using the blitter (see later) and perform parallax
  1547. scrolling or even two-direction scrolling!
  1548.  
  1549.  
  1550. Hardware:Sprite Management
  1551.  
  1552.  
  1553. This section has not been thoroughly tested by me for all of the possibili-
  1554. ties, because I haven't had occasion to use hardware sprites yet. However,
  1555. a mini-preamble will serve to open up ideas.
  1556.  
  1557.     Denise, the chip responsible for sprite management, is a high-speed
  1558. sprite processor using its own DMA channels (8 in all). The existence of 8
  1559. DMA channels for sprite processing does NOT limit the programmer to 8 sprites
  1560. as on some lesser systems, and with clever programming it is possible to have
  1561. up to 72 sprites moving about at once! But before explaining sprite DMA chan-
  1562. nel reuse, the technique allowing this, the fundamentals should be covered.
  1563.  
  1564.     First, some limitations. A hardware sprite has a maximum width of
  1565. 16 pixels. It can be any size vertically up to the size of the entire screen
  1566. if wanted, though usually programmers work with 16x16 sprites or similar. A
  1567. sprite can be displayed anywhere on the screen, and appears in front of the
  1568. playfields. The Intuition mouse pointer is a hardware sprite, in actual fact
  1569. sprite 0, and the DMA allocation within a raster line never allows the time
  1570. allocated to sprite 0 to be stolen by bitplane DMA. If no other sprites are
  1571. used, the remaining sprite DMA slots CAN be stolen by bitplane DMA for really
  1572. wide displays, but it is a good idea not to do this during first experimenta-
  1573. tion with sprite management.
  1574.  
  1575.     Also, a sprite is normally a 3-colour entity. It is possible to have
  1576. a 15-colour sprite by combining two sprites together. The restriction here is
  1577. that the sprites MUST be combined as follows:sprite 0 with sprite 1, sprite 2
  1578. with sprite 3, sprite 4 with sprite 5, and sprite 6 with sprite 7. No other
  1579. order is allowed.
  1580.  
  1581.     Sprite colours are allocated differently for 3-colour sprites and
  1582. 15-colour sprites. For 3-colour sprites, the allocations are:
  1583.  
  1584.     Sprite No    Colour Registers
  1585.     ---------    ----------------
  1586.        0,1        17,18,19 (16 not used)
  1587.        2,3        21,22,23 (20 not used)
  1588.        4,5        25,26,27 (24 not used)
  1589.        6,7        29,30,31 (28 not used)
  1590.  
  1591. The unused colours are treated as 'transparent', i.e., the playfield data
  1592. shows through where 'colour 0' pixels appear in the sprite, the 'colour 0'
  1593. for each sprite being thought of as corresponding to the unused colour reg-
  1594. isters. So, if sprite 0 has pixel colours 0,1,2,3, the actual colours used
  1595. are transparent,17,18,19. Needless to say, colours will only clash with the
  1596. other graphic objects on 5-bitplane screens, extra-halfbrite or HAM screens
  1597. in single-playfield mode. If your screen is 4 bitplanes or less, sprite col-
  1598. ours are independent of the main screen colours.
  1599.  
  1600.     To put sprites on screen, almost all that is required is that the
  1601. programmer constructs a sprite data list in CHIP RAM, and passes a pointer
  1602. to the start of the sprite data list to Denise's sprite control registers.
  1603. Once that has been done, the DMA system handles the sprite all by itself.
  1604. A sprite data list consists of two control words, followed by the sprite
  1605. data itself, and then two more control words, which for a standard sprite
  1606. are zero to tell Denise that no more sprite processing is to be performed
  1607. using this DMA channel.
  1608.  
  1609.     The initial two control words tell Denise where the sprite is to
  1610. be displayed, and also if two 3-colour sprites are combined to form one 15-
  1611. colour sprite.
  1612.  
  1613.     Now the bad news. Allocation of bits in the sprite control words is
  1614. awkward to say the least. It runs as follows:
  1615.  
  1616.  
  1617.     Control Word 1    : EEEEEEEEHHHHHHHH
  1618.  
  1619.     Control Word 2    : LLLLLLLLA0000ELH
  1620.  
  1621.  
  1622. The E bits represent the first line of the sprite (called VSTART). Control
  1623. word 1 contains bits E7-E0 reading left to right, and control word 2 contains
  1624. E8. Bits E8-E0 make up the VSTART parameter.
  1625.  
  1626.     The H bits represent the horizontal position of the sprite. Control
  1627. word 1 contains H8-H1 reading from left to right, and control word 2 contains
  1628. H0. Bits H8-H0 make up the horizontal position parameter, called HSTART.
  1629.  
  1630.     The L bits represent the last line of the sprite plus one. Control
  1631. word 2 contains L7-L0 in the high byte, reading from left to right, and L8 at
  1632. bit 1 of the low byte. I told you it was bloody awkward! This value is known
  1633. as VSTOP.
  1634.  
  1635.     The A bit in the second control word is the ATTACH bit. It tells the
  1636. sprite DMA system that this sprite is attached to another sprite, and is set
  1637. if this is the case (BUT ONLY IN THE SPRITE DATA LISTS FOR SPRITES 1,3,5,7!).
  1638. The comment in the Amiga System Programmer's Guide that these bits are divid-
  1639. ed somewhat impractically between these two control words is a masterpiece of
  1640. understatement!
  1641.  
  1642.     Sprite resolution is one low-resolution pixel horizontally, and one
  1643. raster line vertically, and these values are constant since sprite DMA is in-
  1644. dependent of the playfield modes.
  1645.  
  1646.     Now, the sprite data list is formed as follows for a single sprite:
  1647.  
  1648.  
  1649.         Control Word 1, Control Word 2
  1650.  
  1651.         Data Word 1 of L1, Data Word 2 of L1
  1652.         Data Word 1 of L2, Data Word 2 of L2
  1653.         Data Word 1 of L3, Data Word 2 of L3
  1654.         Data Word 1 of L4, Data Word 2 of L4
  1655.  
  1656.             ...    ...
  1657.  
  1658.         Data Word 1 of LN, Data Word 2 of LN
  1659.  
  1660.         Zero Word, Zero Word.
  1661.  
  1662.  
  1663. The sprite data is treated as being like mini bit planes, the data word 1
  1664. corresponding to 'bitplane 1' of the sprite, and data word 2 corresponding to
  1665.  'bitplane 2' of the sprite. If a given bit in both words is 0, that pixel of
  1666. the sprite is transparent, else the colour allocation is as given in the 3-
  1667. colour sprite allocation table above. This preamble goes a long way toward
  1668. explaining why I haven't bothered with them up to now!
  1669.  
  1670.     Now, if the ATTACH bit is set in sprite 1, this tells Denise that
  1671. sprite 1 is attached to sprite 0 to make a 15-colour sprite. In this case,
  1672. the sprite is treated as a '4-bitplane' entity, and the allocations are:
  1673.  
  1674.  
  1675.         Data word 1, sprite 0 : 'bitplane 1'
  1676.         Data word 2, sprite 0 : 'bitplane 2'
  1677.         Data word 1, sprite 1 : 'bitplane 3'
  1678.         Data word 2, sprite 1 : 'bitplane 4'
  1679.  
  1680.  
  1681. The same applies to the other sprites in combination in ascending numerical
  1682. order (PHEW!).
  1683.  
  1684.     At this point, I warn the reader that if the sprite positions of
  1685. attached sprites do not match, Denise treats them as two separate sprites
  1686. anyway. POSITIONS OF ATTACHED SPRITES MUST BE IDENTICAL FOR THEM TO BE TREA-
  1687. TED AS ATTACHED SPRITES!
  1688.  
  1689.     The colour allocations for a 15-colour sprite are transparent, then
  1690. all colour registers from 17 to 31 upwards, according to the value extracted
  1691. from a given bit position in each sprite data word. If, for example, bit 4 of
  1692. each sprite data word is 1,0,1,1 in the order above, this corresponds to a
  1693. colour value of %1101 or 13, and colour register 29 provides the colour value
  1694. for this pixel of the sprite. The colour register is 16+pixel value, unless
  1695. the pixel is %0000, in which case it's transparent. Again, PHEW!
  1696.  
  1697.     Sprite DMA channel reuse:I mentioned earlier that it was possible to
  1698. display many sprites using the phrase 'sprite DMA channel reuse'. This means
  1699. that the two end control words of the sprite are not zero. To reuse a sprite
  1700. DMA channel, append the entire sprite data list of a second sprite onto the
  1701. first, replacing the zero control words of the first sprite with the starting
  1702. control words of the second. Again, if no more sprites are to be displayed,
  1703. the final control words of the entire list are zero, else the procedure of
  1704. appending a sprite data list continues for as many sprites as required, bear-
  1705. ing in mind an important limitation:there must be at least one raster line
  1706. between sprites thus appended into a reuse list, to give the DMA time to
  1707. read in the new control words.
  1708.  
  1709.     Ok, what if you don't want to use all 8 sprites? well, turning on
  1710. sprite DMA activates all 8 sprite DMA channels, and so the unused ones must
  1711. be passed a pair of zero control words to render them inactive. One can use
  1712. the existing zero control words at the end of some genuine sprites for this
  1713. purpose.
  1714.  
  1715.     Now for the important part. You have created your sprite data lists
  1716. and want to see them activated. Write the address of the start of each of
  1717. your sprite lists to the SPRxPTH/L register pairs. The offsets for each of
  1718. these registers are:
  1719.  
  1720.  
  1721.         SPR0PTH    : offset $120
  1722.         SPR0PTL    : offset $122
  1723.         SPR1PTH    : offset $124
  1724.         SPR1PTL    : offset $126
  1725.         SPR2PTH    : offset $128
  1726.         SPR2PTL    : offset $12A
  1727.         SPR3PTH    : offset $12C
  1728.         SPR3PTL    : offset $12E
  1729.         SPR4PTH    : offset $130
  1730.         SPR4PTL    : offset $132
  1731.         SPR5PTH    : offset $134
  1732.         SPR5PTL    : offset $136
  1733.         SPR6PTH    : offset $138
  1734.         SPR6PTL    : offset $13A
  1735.         SPR7PTH    : offset $13C
  1736.         SPR7PTL    : offset $13E
  1737.  
  1738.  
  1739. This can be done using the Copperlist as might be expected, or the hard way
  1740. using the 68000. In any case, initialisation of all of these pointers MUST
  1741. be performed in the vertical blank interval if sprite DMA is enabled even if
  1742. the registers are pointed at zero control words to disable them. Furthermore
  1743. the values stored in these registers change during sprite DMA usage, and so
  1744. every time the vertical blank interval occurs, the SPRxPTH/L registers must
  1745. be re-initialised, either by the 68000 or using a Copperlist.
  1746.  
  1747.     Moving the sprites by changing the position data in the initial con-
  1748. trol words must also be performed during the vertical blank interval to en-
  1749. sure that Denise receives the correct data, else your sprites could jump all
  1750. over the screen in a weird and wonderful fashion! You can use the Copper int-
  1751. errupt to signal that it's safe to change them if using a Copperlist to init-
  1752. ialise the SPRxPTH/L values, by ensuring that the change only occurs AFTER
  1753. the Copper has initialised the registers. Upon initialisation, the control
  1754. words are read immediately & held for processing until the correct beam pos-
  1755. ition has been reached for displaying them, and once read, the values in the
  1756. sprite data lists can be changed safely.
  1757.  
  1758.     Sprite and Playfield Priority:Having introduced the reader to the
  1759. hellish delights of the Sprite management system's basic control registers, I
  1760. now wish to make life even more complex by introducing sprite/playfield pri-
  1761. ority allocation.
  1762.  
  1763.     First of all, the lower the sprite number, the higher the priority.
  1764. This means that sprite 0 hs higher priority than sprite 1, etc., and that the
  1765. sprites are displayed as though they were on separate planes, the plane for
  1766. sprite 0 being in front of the other sprite planes. In actuality, the sprite
  1767. priorities are grouped into the same pairs as for sprite attachment, particu-
  1768. larly when the playfields are brought into the whole picture.
  1769.  
  1770.     So, considering the sprites as paired for priority purposes, in the
  1771. same manner as for sprite attachment, a playfield can be arranged in order
  1772. of priority according to the table below. In this table, P represents the
  1773. playfield, and the digit pairs 01, 23, etc., represent the sprite pairs. All
  1774. possible combinations are given below, the element to the left of the pri-
  1775. ority arrangement entry list being that with the highest priority.
  1776.  
  1777.  
  1778.     Playfield Pos        Priority Arrangement
  1779.     -------------        --------------------
  1780.  
  1781.          0            P   01  23  45  67
  1782.          1            01   P  23  45  67
  1783.          2            01  23  P   45  67
  1784.          3            01  23  45  P   67
  1785.          4            01  23  45  67  P
  1786.  
  1787.  
  1788. Now, if only one playfield is selected, then this table holds for that play-
  1789. field. If dual playfield mode is selected, then this table holds for each of
  1790. the playfields INDEPENDENTLY (with a few limitations). The selection of the
  1791. priorities is controlled by BPLCON2 (offset $104), whose bits are allocated
  1792. as follows:
  1793.  
  1794.  
  1795.         Bit        Function
  1796.         ---        --------
  1797.  
  1798.         15-7        Unused
  1799.         6        Playfield Relative Priority
  1800.         5-3        Priority of Playfield 2 rel. to sprites
  1801.         2-0        Priority of Playfield 1 rel. to sprites
  1802.  
  1803.  
  1804. If bit 6 of this word is set in dual-playfield mode, playfield 2 is deemed
  1805. to have higher priority than playfield 1, else playfield 1 has priority over
  1806. playfield 2 (the usual state of affairs). Bits 5-3 determine the priority of
  1807. playfield 2 relative to the sprites, and the 3-bit value to insert here is
  1808. the value in the sprite/playfield priority table above labelled 'Playfield
  1809. Pos', corresponding to the given sprite/playfield priority in the table. In
  1810. the same way, the 3-bit value for bits 2-0 determining the priority of play-
  1811. field 1 relative to the sprites is chosen from the above table.
  1812.  
  1813.     Now, since the two playfields have a relative priority, and each of
  1814. the playfields has its own independent priority relative to the sprites, it
  1815. is a fair question to ask whether the playfields' priority relative to each
  1816. other has precedence over their priority relative to the sprites. The answer
  1817. is YES. In the Amiga System Programmer's Guide, an example is given for the
  1818. value BPLCON2 = $0003. Here, bit 6 is zero, so playfield 1 should be in front
  1819. of playfield 2. Bits 5-3 are zero, so playfield 2 should appear in front of
  1820. all sprites from 0-7. Bits 2-0 have the value 3, meaning that playfield 1 is
  1821. in front of sprites 6 & 7, and behind all of the others. A quick glance at
  1822. this description shows something amiss. Playfield 2 cannot be in front of all
  1823. sprites and at the same time behind playfield 1 (which is behind sprites 0 to
  1824. 5). When one of the sprites 0-5 is BETWEEN playfields 1 and 2, it appears in
  1825. front of playfield 1, according to its priority. Since this is in front of
  1826. playfield 2, the sprite is visible at this point, although it must actually
  1827. be behind playfield 2. If only playfield 2 and the sprite are at a given pos-
  1828. ition, playfield 2 covers the sprite because of its priority.
  1829.  
  1830.     In single playfield mode, the bit 6-3 have no function, and should
  1831. be set to zero. Bits 2-0 still control sprite priorities, and the position of
  1832. the single playfield relative to the sprites.
  1833.  
  1834.     Sprite Collision:those readers wishing that they had never bothered
  1835. with sprite handling after reaching this point due to the complexity of the
  1836. sprite management system are about to burst into tears over sprite collision.
  1837. Firstly, let us overview the basic principles of object collision.
  1838.  
  1839.     The fundamental principle of graphic element collision is this:when
  1840. two graphic elements overlap at a screen position, and both objects have a
  1841. set pixel at the same screen position, this is treated as a collision bet-
  1842. ween the two graphic elements. More sophisticated collision algorithms for
  1843. certain purposes do exist, but these will be ignored here, as they are not
  1844. implemented in the Amiga hardware, as will the coordinate comparison algo-
  1845. rithm (which is simpler still in some respects and very quick if speed is of
  1846. the essence).
  1847.  
  1848.     When a collision between graphic elements occurs on the Amiga, it
  1849. is signalled by setting a bit in the CLXDAT register (offset $00E), which is
  1850. a read-only register from the 68000's point of view (only the sprite manage-
  1851. ment and blitter DMA can write to this register). The bit allocations of
  1852. CLXDAT are as follows:
  1853.  
  1854.  
  1855.         Bit        Function
  1856.         ---        --------
  1857.         15        Unused
  1858.         14        Sprite 4/5 collides with sprite 6/7
  1859.         13        Sprite 2/3 collides with sprite 6/7
  1860.         12        Sprite 2/3 collides with sprite 4/5
  1861.         11        Sprite 0/1 collides with sprite 6/7
  1862.         10        Sprite 0/1 collides with sprite 4/5
  1863.          9        Sprite 0/1 collides with sprite 2/3
  1864.          8        Playfield 2 collides with sprite 6/7
  1865.          7        Playfield 2 collides with sprite 4/5
  1866.          6        Playfield 2 collides with sprite 2/3
  1867.          5        Playfield 2 collides with sprite 0/1
  1868.          4        Playfield 1 collides with sprite 6/7
  1869.          3        Playfield 1 collides with sprite 4/5
  1870.          2        Playfield 1 collides with sprite 2/3
  1871.          1        Playfield 1 collides with sprite 0/1
  1872.          0        Playfield 1 collides with playfield 2
  1873.  
  1874.  
  1875. The rules for collision detection are that any non-transparent sprite pixel
  1876. can cause a collision to be registered. However, it is possible to decide by
  1877. appropriate programming to choose which playfield bitplanes are used in the
  1878. determination of collision detection. Also, it is possible to include or ex-
  1879. clude any odd-numbered sprite from collision detection. Which graphic ele-
  1880. ments are used for collision detection purposes is decided by programming the
  1881. CLXCON register (offset $098), which is a write-only register from the point
  1882. of view of the 68000. The bit allocations for CLXCON are as follows:
  1883.  
  1884.  
  1885.         Bit        Function
  1886.         ---        --------
  1887.         15        Enable collision detection, sprite 7
  1888.         14        Enable collision detection, sprite 5
  1889.         13        Enable collision detection, sprite 3
  1890.         12        Enable collision detection, sprite 1
  1891.         11        Use bitplane 6 for collision detection
  1892.         10        Use bitplane 5 for collision detection
  1893.          9        Use bitplane 4 for collision detection
  1894.          8        Use bitplane 3 for collision detection
  1895.          7        Use bitplane 2 for collision detection
  1896.          6        Use bitplane 1 for collision detection
  1897.          5        Bitplane 6 collision match bit
  1898.          4        Bitplane 5 collision match bit
  1899.          3        Bitplane 4 collision match bit
  1900.          2        Bitplane 3 collision match bit
  1901.          1        Bitplane 2 collision match bit
  1902.          0        Bitplane 1 collision mask bit
  1903.  
  1904.  
  1905. The first problem the programmer encounters is that collisions between adja-
  1906. cent numbered sprites used for sprite attachment cannot be performed. Thus
  1907. a collision between sprites 0 and 1, for example, will not be registered in
  1908. the CLXDAT register. Collisions between sprite 0 and any sprite from 2 to 7,
  1909. or between sprite 1 and sprites 2 to 7, will be registered if the appropriate
  1910. control bits are set. If the bit to enable sprite 1 collision detection is
  1911. cleared, only sprite 0 collisions between other sprites and/or the playfields
  1912. will be reported. If the bit is set, then BOTH sprite 0 AND sprite 1 collis-
  1913. ions will be reported, and furthermore reported in the same CLXDAT bit! Thus
  1914. choice of sprites needs to be handled carefully if distinctions between the
  1915. sprites are important for collision purposes, because in the example I have
  1916. just cited, sprites 0 & 1 use the same bit of CLXDAT for collision detection
  1917. and thus telling them apart is impossible by merely scanning CLXDAT. If two
  1918. sprites have been combined into a single 15-colour sprite using the ATTACH
  1919. bit, the corresponding bits for odd sprite collision detection must be set
  1920. in CLXCON in order for collision detection to be performed correctly.
  1921.  
  1922.     For the playfields, the level of control is much more complete. If a
  1923. given bit is set in the CLXCON register above from bits 11 to 6, the relevant
  1924. bitplanes will be used in collision detection. Bits 5 to 0 are called Match
  1925. Bit Plane Value bits, and are used to determine what values to use for the
  1926. comparison before reporting collision detection. 
  1927.  
  1928.     Let us assume that we are using 6 bitplanes, and that the BPLCON0
  1929. value has enabled all 6 bitplane DMA channels (see the Bitplane Control sec-
  1930. tion above). If one of the bits 11 to 6 (called the Enable Bitplane bits)
  1931. is set, that bitplane is used. The corresponding match bit (bits 5 to 0) in
  1932. the CLXCON register is then used to compare with the given pixel. Let us ass-
  1933. ume that the Enable bit for bitplane 3 (bit 8 of CLXCON) is set. If the value
  1934. of the pixel data on bitplane 3 at the collision detection point MATCHES the
  1935. value of the match bit for bitplane 3 in CLXCON (bit 2) then a collision is
  1936. reported. So if the pixel bit is 0, and the match bit is 0 also, the collis-
  1937. ion is reported, as in the case when the pixel bit is 1 and the match bit in
  1938. CLXCON is 1. If we don't care about a particular bitplane (say for example we
  1939. wish to ignore bitplane 1 altogether for collision detection), clear the En-
  1940. able bitplane bit for bitplane 1 (bit 6). Now, the value of bit 0 of CLXCON
  1941. doesn't matter-the collision will be reported regardless of the state of
  1942. the pixels on bitplane 1.
  1943.  
  1944.     The table given in the Amiga Systems Programmer's Guide is repro-
  1945. duced here for those who want it. It correlates directly with the above des-
  1946. cription of bitplane selection & collision detection control. The Enable Bit-
  1947. plane bits are referred to as ENBPx, the Match Bitplane Value bits as MVBPx.
  1948. The 'xx' bits in the table below are "don't care" bits-they can be either 0
  1949. or 1.
  1950.  
  1951.  
  1952.     ENBPx    MVBPx    Collision possible with bit pattern
  1953.     -----    -----    -----------------------------------
  1954.  
  1955.     111111    111111    111111 only
  1956.     111111    111000    111000 only
  1957.     111100    1111xx    111100, 111101, 111110, 111111 only
  1958.     011111    x00000    000000, 100000 only
  1959.     000000    xxxxxx    Any bit pattern!!!
  1960.  
  1961.  
  1962. Take note, that if fewer than 6 bitplanes are used, the ENBPx bits for the
  1963. unused bitplanes MUST be set to zero!
  1964.  
  1965.     Needless to say, if the colours are chosen suitably, various colli-
  1966. sion strategies based upon colour can be constructed, as well as strategies
  1967. based directly upon bitplane management. It is possible, for example, to set
  1968. sprite collision to register with only red and green pixels of a playfield,
  1969. or collision with the transparent points of playfield 1 to register only if
  1970. the underlying pixels of playfield 2 are black.
  1971.  
  1972.     Spurious Sprite Video Data:occasionally software that directly con-
  1973. trols the hardware suffers from the appearance of a line down the screen at
  1974. some point. Analysis usually (but not always) shows that this line corres-
  1975. ponds in position to the position of the CLI sprite pointer prior to swit-
  1976. ching off sprite DMA. If this is done before the sprite management system has
  1977. finished displaying the CLI sprite pointer, then when sprite DMA is turned
  1978. off, the sprite management system cannot read the end control words, and thus
  1979. continues displaying the sprite data onscreen. Even when sprite DMA is re-
  1980. enabled, the contents of the sprite data pointers may not point to zero con-
  1981. trol words, in which case spurious sprite video data may continue to appear
  1982. until the sprite data pointers are changed.
  1983.  
  1984.     There are two ways to prevent this. The first technique is to point
  1985. the sprite data pointer registers at zero control words. The second technique
  1986. (thanks to Count Zero) is to wait for the electron beam to reach a position
  1987. beyond the maximum possible display position of the CLI sprite pointer, and
  1988. then turn off the sprite DMA (use a raster line value of 300 for PAL Amigas).
  1989.  
  1990.     Other Sprite Registers:there exist other sprite data registers, that
  1991. are normally accessed by the sprite management system DMA alone. These regis-
  1992. ters can be accessed in software by the 68000 also, and these registers are:
  1993.  
  1994.  
  1995.         SPR0POS        (offset $140)
  1996.         SPR0CTL        (offset $142)
  1997.         SPR0DATA        (offset $144)
  1998.         SPR0DATB        (offset $146)
  1999.  
  2000.            ...            ...
  2001.  
  2002.         SPR7POS        (offset $178)
  2003.         SPR7CTL        (offset $17A)
  2004.         SPR7DATA        (offset $17C)
  2005.         SPR7DATB        (offset $17E)
  2006.  
  2007.  
  2008. The registers for SPRxPOS onwards occupy the entire range of offsets from
  2009. $140 to $17E, in ascending sprite number order.
  2010.  
  2011.     When the programmer assigns sprite management control to the stan-
  2012. dard sprite management DMA channels, the sequence of events is:
  2013.  
  2014.  
  2015.     1) DMA system loads two control words into SPRxPOS (control
  2016.        word 1) and SPRxCTL (control word 2).
  2017.  
  2018.     2) DMA system turns off sprite output.
  2019.  
  2020.     3) DMA controller waits for the electron beam to reach the
  2021.        value in the VSTART portion of the sprite control words.
  2022.  
  2023.     4) Once this position is reached, data words are written
  2024.        into SPRxDATA and SPRDATB.
  2025.  
  2026.     5) DMA controller turns on sprite output again, and the
  2027.        values in SPRxDATA and SPRxDATB are used for the
  2028.        current raster line. These are positioned according to
  2029.        the HSTART value.
  2030.  
  2031.     6) DMA controller continues reading data into SPRxDATA/B
  2032.        and displaying it until the VSTOP value is reached.
  2033.  
  2034.     7) The DMA controller reads the two control words at the
  2035.        end of the sprite data list. If these are non-zero, the
  2036.        sprite data channel is being re-used, and the sequence
  2037.        of events begins again at 1).
  2038.  
  2039.     8) If the DMA system encounters the two zero control words
  2040.        at the end of the sprite data list, the DMA controller
  2041.        turns off sprite data output on this DMA channel until
  2042.        the vertical blank interval occurs, at which point the
  2043.        sprite DMA begins its display sequence at 1) again.
  2044.  
  2045.  
  2046. If the programmer uses the 68000 to access these registers, normally used
  2047. solely by the DMA controller (but accessible to the 68000), then there are
  2048. a few changes to take note of. First, the sprite data pointer registers need
  2049. to be initialised as for sprite management via DMA-this remains the same.
  2050. The sprite data list contents change somewhat, however. If the 68000 is used
  2051. to load the SPRxPOS/SPRxCTL registers, then only the HSTART value in the
  2052. sprite data list control words, plus the value of the ATTACH bit, need to be
  2053. valid. VSTART and VSTOP are used only by the DMA controller.
  2054.  
  2055.     Sprite data output can then being by writing data to the SPRxDATA/B
  2056. registers. Write to SPRxDATB first, as writing to SPRxDATA causes the data
  2057. from both registers to be output to the screen. Note that if the DMA control-
  2058. ler is bypassed in this way, that fresh data needs to be supplied for each
  2059. line of the sprite to the SPRxDATA/B registers if needed (normally this is
  2060. performed by the DMA controller) unless all that is wanted is a solid column
  2061. of identical pixel data.
  2062.  
  2063.     To turn off the sprite again, simply write some value to SPRxPOS. I
  2064. suggest writing the value zero.
  2065.  
  2066.  
  2067. Hardware:The Blitter
  2068.  
  2069.  
  2070. The blitter is THE chip that makes the Amiga so special, and it will come as
  2071. no surprise to realise that this section will probably be the largest section
  2072. in this file. It has the capacity to move data at a peak speed of 16 million
  2073. pixels per second, perform logical operations upon its data sources before
  2074. generating its output, and is used for three principal functions:
  2075.  
  2076.  
  2077.     1) Transferring rectangular graphic data blocks to screen
  2078.        bitplane memory (with logical operations to change the
  2079.        plotting method)
  2080.  
  2081.     2) Drawing lines between any two points on screen
  2082.  
  2083.     3) Filling bounded areas (taking account of some restrictions)
  2084.        to create filled polygon shapes
  2085.  
  2086.  
  2087. This is not its entire repertoire, however. The blitter contains all of the
  2088. on-chip logic necessary to perform vector-arcitecture mathematics, but is
  2089. prevented from doing so directly by its hard-wired design. However, it is
  2090. possible to make the blitter perform high-speed computational functions on
  2091. large blocks of data in one go, provided that one is familiar with Boolean
  2092. Algebra and has at least a first-year university level grounding in formal
  2093. logic up to the level of alternational normal schemata (I recommend as THE
  2094. definitive text on formal logic for those interested to be 'Methods In Logic'
  2095. by Willard Van Ormand Quine - ask for the Library of Congress record number
  2096. in preference to the ISBN number as it's an American publication).
  2097.  
  2098.     Having whetted the appetite, now comes a small amount of bad news.
  2099. The blitter is powerful, but its power has associated with it a certain am-
  2100. ount of complexity. In particular, although it has a well-defined set of
  2101. registers for function control, the bit allocations of the BLTCONx control
  2102. registers (see register list below) change dramatically with each function.
  2103. There are also several rigid conventions to follow, otherwise the blitter
  2104. may just scribble at high speed all over critical program memory, as once
  2105. started up, it cannot be stopped halfway.
  2106.  
  2107.     Blitter Register List:the list of registers associated with the
  2108. blitter is:
  2109.  
  2110.  
  2111.     Register    Offset        Function
  2112.     --------    ------        --------
  2113.  
  2114.     BLTDDAT      000        Blitter Data D (read-only!)
  2115.  
  2116.     BLTCON0      040        Blitter Control Register 0
  2117.     BLTCON1      042        Blitter Control Register 1
  2118.  
  2119.     BLTAFWM      044        Blitter A first word mask
  2120.     BLTALWM      046        Blitter A last word mask
  2121.  
  2122.     BLTCPTH      048        Source C data pointer high word
  2123.     BLTCPTL      04A        Source C data pointer low word
  2124.     BLTBPTH      04C        Source B data pointer high word
  2125.     BLTBPTL      04E        Source B data pointer low word
  2126.     BLTAPTH      050        Source A data pointer high word
  2127.     BLTAPTL      052        Source A data pointer low word
  2128.     BLTDPTH      054        Destination D data pointer high word
  2129.     BLTDPTL      056        Destination D data pointer low word
  2130.  
  2131.     BLTSIZE      058        Controls data size/starts blitter
  2132.  
  2133.     BLTCMOD      060        Source C modulo register
  2134.     BLTBMOD      062        Source B modulo register
  2135.     BLTAMOD      064        Source A modulo register
  2136.     BLTDMOD      066        Destination D modulo register
  2137.  
  2138.     BLTCDAT      070        Blitter Source C Data
  2139.     BLTBDAT      072        Blitter Source B Data
  2140.     BLTADAT      074        Blitter Source A Data
  2141.  
  2142.  
  2143. Some of these registers are not accessed during standard blitter usage. They
  2144. do come into play for some of the less well-publicised functions for which
  2145. the blitter is used. More of this later.
  2146.  
  2147.     Rectangular Data Block Moving:this is the first blitter function to
  2148. be dealt with in this section, and a preamble will help introduce certain key
  2149. concepts.
  2150.  
  2151.     The blitter, when operating in data copy mode, takes data from up to
  2152. three different source areas of memory, combines them using a logical opera-
  2153. tion, and then writes the data out to the destination memory area. The main
  2154. use of this function is for copying large blocks of graphic data to bitplane
  2155. memory for display, or copying portions of bitplane memory to safe off-screen
  2156. areas for background saving.
  2157.  
  2158.     In general, the source memory is linearly organised, and the graphic
  2159. data occurs in sequential words in memory. At this point I stress that the
  2160. blitter is a WORD-based device, and that all of the blitter's activities are
  2161. based upon word-aligned memory, just like the 68000's program access. Return-
  2162. ing to the graphic data, this linear organisation means that the data can be
  2163. read sequentially without any problems.
  2164.  
  2165.     However, to illustrate the blitter methodology, let there exist a
  2166. low-resolution screen of one bitplane, and some graphic data that is to be
  2167. written to the screen. The low-resolution bitplane is 40 bytes across, or 20
  2168. words, and the graphic data has a maximum width of 48 pixels (3 words). The
  2169. pointer to the word on the screen bitplane where the data is to be put is
  2170. written to the BLTDPTH/L registers, and the pointer to the graphic data is
  2171. written to the BLTAPTH/L registers. For now let us ignore other sources and
  2172. the actual details of the logical operation used. The blitter functions by
  2173. using the address pointers to fetch a data word from each source (here we are
  2174. using one source only, source A), and after processing it internally, uses
  2175. the pointer to the destination to write the data to the screen. It then inc-
  2176. rements the pointers by 2 to access the next word. So for each blitter oper-
  2177. ation, the pointers MUST be re-initialised (unless they happen to end up
  2178. pointing to memory areas to be referenced by another blitter operation, in
  2179. which case the blitter can simply be started up again).
  2180.  
  2181.     For the graphic data, this poses no problem, since it is sequential-
  2182. ly organised in memory. But after writing 3 words of data, the blitter must
  2183. have a correction added to the destination pointer to point to the next ras-
  2184. ter line to write to. This correction is called the modulo, and is stored in
  2185. the modulo register for the appropriate source and destination. In this exam-
  2186. ple, the blitter needs to have a correction of 17 words added to the destina-
  2187. tion pointer to reference the screen memory correctly, or 34 bytes. Thus the
  2188. modulo for the destination, BLTDMOD, is set to 34. The modulo for source A,
  2189. BLTAMOD, is set to zero. If other sources are used, the appropriate modulo
  2190. must be selected. If source B is used as a graphic data mask organised in the
  2191. same way as the actual pixel data, its modulo is again zero. If the source C
  2192. is used as a reference to the screen for background masking-in, its modulo
  2193. must be the same as the destination modulo, i.e., 34 in this example.
  2194.  
  2195.     So, the organisation of source and destination memory needs to be
  2196. analysed before setting up both the BLTxPTH/L registers, and the BLTxMOD reg-
  2197. isters. This information should be sufficient to cover initialisation of the
  2198. registers just mentioned.
  2199.  
  2200.     Now we need to decide how much data to transfer. The blitter accepts
  2201. this information as a single word, coded as follows:
  2202.  
  2203.  
  2204.         HHHHHHHHHHWWWWWW
  2205.  
  2206.  
  2207. The H bits represent the height of the graphic data. This can take any value
  2208. from 0 to 1023 lines. Zero is taken to mean the maximum size of 1024 lines,
  2209. as a value of zero lines is otherwise silly. The W bits represent the width
  2210. of the graphic data in memory words, in our example this is 3. So if our data
  2211. is 40 raster lines deep, the value of the H bits is 40, and the value of the
  2212. W bits is 3. This gives a final value of
  2213.  
  2214.  
  2215.         (40 * 64) + 3 = $0A03
  2216.  
  2217.  
  2218. This value is written to the BLTSIZE register in the table above. The method
  2219. I use for computing BLTSIZE is something of the order of
  2220.  
  2221.  
  2222.         move.w    rows(a0),d0    ;no of raster lines
  2223.         and.w    #$3FF,d0        ;ensure value is 0-1023
  2224.         lsl.w    #6,d0        ;shift
  2225.         move.w    cols(a6),d1    ;no of WORDS across!
  2226.         and.w    #$3F,d1        ;ensure value is 0-63
  2227.         add.w    d1,d0        ;add it in
  2228.         move.w    d0,BLTSIZE(a5)    ;here a5 contains $DFF000...
  2229.  
  2230.  
  2231.     However, writing to the BLTSIZE register starts the blitter! So this
  2232. must be the LAST operation performed upon the blitter registers for a given
  2233. blitter operation.
  2234.  
  2235.     Now we need to consider logical operations. It is of great assist-
  2236. ance if the programmer has a thorough grounding in Boolean Algebra at this
  2237. point, since the method used by the blitter relies heavily upon this. The
  2238. terminology used for each logical operation selected is 'minterm', which is
  2239. short and sweet. The formal technique for deriving minterms labours under the
  2240. unfortunate name of 'developed alternation normal schema formation', a fair
  2241. mouthful for anyone to handle.
  2242.  
  2243.     The simple way of thinking about this is to remember that the blit-
  2244. ter has 8 possible logical operations hard-wired into it. These operations
  2245. are:
  2246.  
  2247.  
  2248.     ABC    :    A AND B AND C
  2249.     ABc    :    A AND B AND (NOT C)
  2250.     AbC    :    A AND (NOT B) AND C
  2251.     Abc    :    A AND (NOT B) AND (NOT C)
  2252.     aBC    :    (NOT A) AND B AND C
  2253.     aBc    :    (NOT A) AND B AND (NOT C)
  2254.     abC    :    (NOT A) AND (NOT B) AND C
  2255.     abc    :    (NOT A) AND (NOT B) AND (NOT C)
  2256.  
  2257.  
  2258. The next table shows which of the operations produce a 1 (true) bit output
  2259. dependent upon the values of the input bits:
  2260.  
  2261.  
  2262.     Operation    A B C    LFx Bit No.
  2263.     ---------    - - -    ----------
  2264.        ABC        1 1 1         7
  2265.        ABc        1 1 0         6
  2266.        AbC        1 0 1         5
  2267.        Abc        1 0 0         4
  2268.        aBC        0 1 1         3
  2269.        aBc        0 1 0         2
  2270.        abC        0 0 1         1
  2271.        abc        0 0 0         0
  2272.  
  2273.  
  2274. When the blitter processes its data from each source, A,B,C, it feeds the
  2275. data into circuits whose outputs are each of the 8 logical operations above.
  2276. These are then ORed together to produce the final result sent to the dest-
  2277. ination memory. Which ones are selected to OR together are under the control
  2278. of the programmer. The LFx bit numbers in the table above are used to select
  2279. them, and a byte containing the approriate bits set selects the given logical
  2280. operation. So, to select ABC+ABc+AbC+Abc, one uses the select byte $F0 (or,
  2281. %11110000 in binary).
  2282.  
  2283.     But how do we select them? In our example, we want the destination
  2284. to match the source input. In other words, D = A. But since B and C are al-
  2285. ways present in the blitter, how do we introduce them? Well, we don't care
  2286. about the state of B, so we want operations containing both AB and Ab. In a
  2287. like manner, we don't care about C, so we want operations containing AC and
  2288. Ac. This is the same as performing the Boolean Algebra operations (here, + is
  2289. taken to mean OR, and AB is taken to mean A AND B):
  2290.  
  2291.  
  2292.         A(B+b) = AB + Ab
  2293.  
  2294.         A(C+c) = AC + Ac
  2295.  
  2296.  
  2297. But we want terms of the form ABC etc. Well, take the first expression
  2298.  
  2299.  
  2300.         A(B+b) = AB + Ab
  2301.  
  2302.  
  2303. and append the (C+c) used in the second:
  2304.  
  2305.  
  2306.         A(B+b)(C+c) = AB(C+c) + Ab(C+c)
  2307.  
  2308.                = ABC +ABc + AbC + Abc
  2309.  
  2310.  
  2311. This just happens to be the example encoded as the select byte $F0 above. The
  2312. principle is the same throughout. Some more examples are:
  2313.  
  2314.  
  2315.         Invert Graphic Data : D = a
  2316.  
  2317.         D = a
  2318.  
  2319.           = a(B+b)(C+c)
  2320.  
  2321.           = aB(C+c) + ab(C+c)
  2322.  
  2323.           = aBC + aBc + abC + abc
  2324.  
  2325.  
  2326. Which is encoded as the select byte $0F.
  2327.  
  2328.  
  2329.         OR in a graphic into the bitplane : D = A + C
  2330.  
  2331.         D = A + C
  2332.  
  2333.           = A(B+b)(C+c) + C(A+a)(B+b)
  2334.  
  2335.           = AB(C+c) + Ab(C+c) + CA(B+b) + Ca(B+b)
  2336.  
  2337.           = ABC + ABc + AbC + Abc + CAB + CAb + CaB + Cab
  2338.  
  2339.           = ABC + ABc + AbC + Abc + ABC + AbC + aBC + abC
  2340.  
  2341.           = ABC + ABc + AbC + Abc + aBC + abC
  2342.  
  2343.  
  2344. Which is encoded as the select byte $FA. Note that where identical terms
  2345. appear in the expression above, surplus ones are simply deleted from the
  2346. expression.
  2347.  
  2348.     The last example I shall give is the so-called 'cookie-cut' opera-
  2349. tion. This name originates from the way cookie biscuits are cut from the
  2350. biscuit mixture when making chocolate chip cookies, familiar to any American
  2351. especially one who has encountered 'Girl Ranger' cookies. This operation is
  2352. one where the data A is masked first. If the data A is 1 at this point, we
  2353. want the masked data to be written. If the data A is 0, we want it to be re-
  2354. garded as transparent, and hence the background to show through. This allows
  2355. the mask to create opaque 0 pixels within the data, and any 0 pixels in the
  2356. A data to be regarded as transparent by having the corrsponding mask pixel
  2357. set to 1. The operation becomes:
  2358.  
  2359.  
  2360.         Cookie cut : D = AB + aC
  2361.  
  2362.         D = AB(C+c) + a(B+b)C
  2363.  
  2364.           = ABC + ABc + aBC + abC
  2365.  
  2366.  
  2367. which encodes as the select byte $CA. In this case, the mask will be a nega-
  2368. tive image (photographically speaking) of the graphic data except where any
  2369. transparent pixels are required.
  2370.  
  2371.     So, we now know how to select which memory areas to transfer, how to
  2372. set modulo values for trasnfer to bitplanes, how to determine the data size
  2373. (and also start the blitter), and select the appropriate logical operation. I
  2374. now wish to intoduce the blitter control registers. These affect the manner
  2375. in which the blitter works. The two blitter control registers, BLTCON0 and
  2376. BLTCON1, have control bits allocated according to the following tables:
  2377.  
  2378.  
  2379.     Bit    BLTCON0 Function
  2380.     ---    ----------------
  2381.  
  2382.     15-12    ASH3-0 : contain the source A shift distance (see later)
  2383.     11-8    USEA-D : select which sources/destination are used
  2384.     7-0    LFx    : logical function selection bits mentioned above
  2385.  
  2386.  
  2387.     Bit    BLTCON1 Function
  2388.     ---    ----------------
  2389.  
  2390.     15-12    BSH3-0 : contain the source B shift distance (see later)
  2391.     11-5    Unused
  2392.     4    EFE    : Exclusive Fill Enable
  2393.     3    IFE    : Inclusive Fill Enable
  2394.     2    FCI    : Fill Carry In
  2395.     1    DESC   : Descending mode
  2396.     0    LINE   : Turn on Line Drawing Mode
  2397.  
  2398.  
  2399. In the case of BLTCON0, the LFx bits that select the minterms have already
  2400. been covered. This leaves the USEA-D bits and the ASH3-0 bits.
  2401.  
  2402.     The USEx bits determine which sources/destination are used. If a
  2403. given USEx bit is set, the DMA control system for that source (or destin-
  2404. ation) is fully enabled, in which case the blitter operation proceeds norm-
  2405. ally as described earlier. If a source is not being used at all, clear the
  2406. appropriate USEx bit. This has the effect of disabling the full effects of
  2407. the DMA channel, but NOT of stopping data transfer altogether. Because of
  2408. this, minterms have to be chosen to effectively ignore the given source, as
  2409. well as clearing the given USEx bit. Instead, the same word contained in
  2410. the BLTxDAT registers for the given source is read continuously and not up-
  2411. dated. This can be used to fill memory with a given value, as follows:
  2412.  
  2413.  
  2414.         move.w    #value,BLTADAT(a5)    ;value to fill
  2415.         move.w    #$01F0,BLTCON0(a5) ;minterms D=A, USED only
  2416.         move.w    #0,BLTCON1(a5)     ;mode = copy data
  2417.  
  2418.         lea    memory_to_fill(pc),a0 ;start of memory area
  2419.  
  2420.         move.l    a0,BLTDPTH(a5)    ;point Blitter at it
  2421.  
  2422.         move.w    #size,BLTSIZE(a5) ;how much to fill & startup!
  2423.  
  2424.  
  2425. If copying graphic data, pick the USEx bits carefully. Ensure that if you ARE
  2426. using a given source, set it's USEx bit. And whatever you do, don't forget to
  2427. set USED to enable the destination output (the number of programmers who have
  2428. forgotten to set USED at some time doesn't bear thinking about) or else the
  2429. blitter won't be able to generate the desired output!
  2430.  
  2431.     The ASH3-0 bits are used to 'fine-tune' the blitter data positioning
  2432. for graphic output. Normally, the blitter can only output its data to a word
  2433. boundary, being a word-oriented device. To enable pixel-boundary data plot-
  2434. ting, the blitter has the ability to shift input data before outputting it.
  2435. The ASH3-0 bits contain the number of bit positions to shift the data from
  2436. source A to the right before outputting it. The bits BSH3-0 in BLTCON1 have
  2437. an almost identical function, this time affecting source B. Hence source A
  2438. is usually chosen to be the graphic data, and source B any mask data used. If
  2439. background data is used for transparency generation, source C is generally
  2440. the preferred choice. Both graphic and mask are shifted before output.
  2441.  
  2442.     Moving on to BLTCON1, for data copying, set all bits other than the
  2443. BSH3-0 bits to zero. These bits are used for line drawing mode and boundary-
  2444. filling mode, covered later.
  2445.  
  2446.     To complete the register list, there are two mask registers for the
  2447. data source A. These are BLTAFWM (Blitter source A first word mask) and
  2448. BLTALWM (Blitter source A last word mask). If these registers are both zero,
  2449. the first and last word of each raster line of copied graphic data will be
  2450. zeroed out-they are used as filter masks for the left and right edges of a
  2451. graphic data block. If the graphic is one data word wide, the two registers
  2452. operate upon the same source A data word, and only those source A bits that
  2453. have the corresponding bits set in BOTH mask registers are allowed through
  2454. unchanged (otherwise they are treated as zero). For wider graphic data blocks
  2455. the mask registers mask the end words of the data. As yet, I have not had
  2456. time to establish conclusively whether source A masking is performed BEFORE
  2457. or AFTER source A data shifting under BLTCON0 control, and as the result is
  2458. critically dependent upon this, I suggest experimentation before assuming one
  2459. way or the other.
  2460.  
  2461.     As a final note concerning the blitter in data copy mode, I said
  2462. above that the remaining BLTCON1 bits other than the BSH3-0 bits should be
  2463. cleared. Normally this is the case (using the blitter for graphic data manip-
  2464. ulation), but if the blitter is used to move memory blocks, particularly if
  2465. the data blocks are overlapping, then it is time to consider setting the
  2466. DESC bit.
  2467.  
  2468.     The DESC bit of BLTCON1 controls whether the address incrementing of
  2469. the BLTxPTH/L registers is positive (ascending mode, DESC=0) or negative (de-
  2470. scending mode, DESC=1). An example illustrates the point. Let us copy a block
  2471. of memory of size N bytes (N will have to be even for blitter copy), starting
  2472. at address X, to a new location at address Y. If X lies lower in memory than
  2473. Y, but the difference between X and Y is less than N bytes, then the initial
  2474. copy operation will erase some of the data at the end of the block to be cop-
  2475. ied. To prevent this, it is possible to copy backwards by setting DESC=1. If
  2476. this is done, however, the pointer registers should be set to addresses X+N
  2477. and Y+N instead of addresses X and Y, because copying will start at the END
  2478. of the blocks.
  2479.  
  2480.     NOTE:until recently, I assumed that the choice of Source A for the
  2481. graphic data, Source B for the mask, and Source C for the background when a
  2482. masked blit was performed was OK. This has transpired to be incorrect. Source
  2483. channel selection SHOULD be:
  2484.  
  2485.         Source A = MASK
  2486.  
  2487.         Source B = DATA
  2488.  
  2489.         Source C = BACKGROUND
  2490.  
  2491. If this order of selection is made, then the standard minterms mentioned in
  2492. the Amiga Hardware Reference Manual hold true, e.g., $CA is the 'cookie-cut'
  2493. minterm. See later for an example.
  2494.  
  2495.     Line Drawing:the blitter has inbuilt line-drawing logic which was
  2496. added by its designer, Jay Miner, after discovering that the other functions
  2497. left space on the silicon for the line-drawing hardware (wow-history lesson
  2498. too!) and decided that this would be a welcome feature to include.
  2499.  
  2500.     The problem with the blitter's line-drawing logic is that it uses a
  2501. method unfamiliar to anyone having no experience of hardware geometry engines
  2502. (a generic term used to describe high-speed graphics-specific processors). A
  2503. line drawn with the blitter has to be described in a manner conforming to the
  2504. method used. I shall try to make this simple, but if it seems hard going, I
  2505. implore you to persevere-this imformation will apply to far more sophistica-
  2506. ted geometry engines as well and hence has a wider application.
  2507.  
  2508.     Lines are represented under normal circumstances using the start and
  2509. end coordinates. If the end points of the line being drawn are P (x1,y1) and
  2510. Q (x2,y2), this is usually sufficient information. The alternative informa-
  2511. tion used by the blitter and other geometry engines is 1) the address of the
  2512. memory word in the bitplane where the start point P lies; 2) the number of
  2513. points that the line will occupy once drawn; 3) the angular orientation of
  2514. the line represented in terms of which 45 degree compass segment (or octant)
  2515. that the said angle lies in (measured anticlockwise from zero degrees from
  2516. the X-axis:in this system of measurement 90 degrees is due North, 180 degrees
  2517. is due West, 270 degrees is due South etc). These compass segments, or oct-
  2518. ants, are defined using octant numbers, allocated according to the table:
  2519.  
  2520.  
  2521.         Angle Range    Octant No.
  2522.         -----------    ---------
  2523.  
  2524.         0-45 degrees        0
  2525.         45-90 degrees        1
  2526.         90-135 degrees        2
  2527.         135-180 degrees        3
  2528.         180-225 degrees        4
  2529.         225-270 degrees        5
  2530.         270-315 degrees        6
  2531.         315-360 degrees        7
  2532.  
  2533.  
  2534.     Note that this table assumes that the Y-axis is drawn to be positive
  2535. when pointing DOWNWARDS, thus setting up the usual screen coordinate system
  2536. where (0,0) is the TOP LEFT CORNER of the screen.
  2537.  
  2538.     The octant information is insufficient in itself, however. Before I
  2539. explain the relationship between the octant numbers and the data actually
  2540. sent to the blitter, I shall give the equations describing the line that are
  2541. used by the blitter. These are :
  2542.  
  2543.  
  2544.         dX = X2 - X1    These are used to determine
  2545.  
  2546.         dY = Y2 - Y1    which octant the line lies in
  2547.  
  2548.         DX = ABS (dX)    DX = Delta X
  2549.  
  2550.         DY = ABS (dY)    DY = Delta Y
  2551.  
  2552.         DS = MIN(DX,DY)    DS = Delta S (smaller Delta)
  2553.  
  2554.         DL = MAX(DX,DY)    DL = Delta L (larger Delta)
  2555.  
  2556.  
  2557. These expressions form the basis of geometry engine line drawing (including
  2558. that of the blitter, even if it cannot be regarded as a true geometry engine
  2559. in the same manner as, for example, the Weitek 1164/1165 series used in the
  2560. 1167 accelerator board for the Compaq DeskPro 386/20 PC, or the TMS34020).
  2561.  
  2562.     Now for the hard part. Delta X, Delta Y and Delta S/L are used to
  2563. determine which octant should be selected for the line. This is done by the
  2564. conversion of the octant number into a 3-bit number, which corresponds to
  2565. three bits in the BLTCON1 register as used for line drawing control. How the
  2566. bits in BLTCON1 are allocated changes when line drawing is performed. The
  2567. bit allocations are:
  2568.  
  2569.  
  2570.     Bit No        Name        Function
  2571.     ------        ----        --------
  2572.  
  2573.     15-12        TEXTURE3-0    Value for mask shifting (see
  2574.                     below)
  2575.     11-7        Unused        Always set to zero
  2576.     6        SIGN        Changes line drawing direction
  2577.     5        Unused        Always set to zero
  2578.     4        SUL        Sometimes Up or Left
  2579.     3        SUD        Sometimes Up or Down
  2580.     2        AUL        Always Up or Left
  2581.     1        SING        Singular bit (see below)
  2582.     0        LINE        Always set to 1 for line
  2583.                     drawing
  2584.  
  2585.  
  2586. The SUD/SUL/AUL bits are set or cleared according to the following values:
  2587.  
  2588.  
  2589.     Octant No.    SUD    SUL    AUL
  2590.     ---------    ---    ---    ---
  2591.         0         1     0     0
  2592.         1         0     0     0
  2593.         2         1     1     0
  2594.         3         0     0     1
  2595.         4         1     0     1
  2596.         5         0     1     0
  2597.         6         1     1     1
  2598.         7         0     1     1
  2599.  
  2600.  
  2601. and the SIGN bit is set if the computed value of (2 * DS) - DL is less than
  2602. zero (to change the direction in which the line is rendered for lines with a
  2603. negative slope).
  2604.  
  2605.     Under normal circumstances, the USEA-D bits in BLTCON0 should be set
  2606. to the values:
  2607.  
  2608.  
  2609.             USEA = 1
  2610.             USEB = 0
  2611.             USEC = 1
  2612.             USED = 1
  2613.  
  2614.  
  2615. and the minterms set to $CA. The value of the ASH3-0 bits is set to the value
  2616.  
  2617.  
  2618.             x1 MOD 16
  2619.  
  2620.  
  2621. to determine which bit in the start word is the start bit of the line, and in
  2622. most literature on blitter line drawing these bits change their name to the
  2623. START3-0 bits.
  2624.  
  2625.     The line can be drawn using a mask, to provide dotted lines accord-
  2626. ing to a line dot pattern. This mask is written to BLTBDAT (see register list
  2627. above), and for solid lines the value to use is $FFFF. A value of $AAAA or
  2628. $5555 produces a finely dotted line, a value of $CCCC a more coarsely dotted
  2629. line.
  2630.  
  2631.     So, to give the blitter register initialisation values. These are as
  2632. follows (noting the values DX, DY, DS and DL above):
  2633.  
  2634.  
  2635.     BLTCPTH/L, BLTDPTH/L    : Put the start address of the first
  2636.                   point of the line in these registers.
  2637.  
  2638.     BLTCMOD, BLTDMOD        : Number of bytes making up one raster
  2639.                   line of the bitplane within which the
  2640.                   line is to be rendered. For a low-res
  2641.                   bitplane this is 40. See example code
  2642.                   below.
  2643.  
  2644.     BLTBMOD            : Set to 2 * DS.
  2645.  
  2646.     BLTAMOD            : Set to (2 * DS) - (2 * DL).
  2647.  
  2648.     BLTAPTL            : Set to (2 * DS) - DL.
  2649.  
  2650.     BLTADAT            : Set to $8000
  2651.  
  2652.     BLTBDAT            : Set to your chosen pattern mask
  2653.  
  2654.     BLTAFWM            : Always set to $FFFF
  2655.  
  2656.     BLTSIZE            : Last register initialised (it sets the
  2657.                   blitter going). Set width bits equal to
  2658.                   2 always. Set height bits equal to DL.
  2659.                   Hence value to use is (DL * 64) + 2.
  2660.  
  2661.     One final point. If the blitter is used to draw the closed border of
  2662. a polygon, which is then to be filled by the blitter in boundary-fill mode as
  2663. documented later, then the line should be drawn with only one pixel set per
  2664. raster line. The blitter provides a line-drawing mode specially for this. To
  2665. draw lines normally, set the SING bit in BLTCON1 to zero, and to draw lines
  2666. in this special mode, set the SING bit to 1.
  2667.  
  2668.     The following code can be etched out of this file, and used at will.
  2669. It is a drawline() routine complete with documentation which illustrates all
  2670. of the above concepts in action. Note, in order to use this code, it is best
  2671. to either kill off the operating system altogether or use Forbid() to ensure
  2672. that your task is the only one running within the system. My test code using
  2673. this kills off Exec, but I haven't included this in case anyone wishes to use
  2674. this code and keep the operating system alive.
  2675.  
  2676.  
  2677. * Blitter Line Drawing Code : Data Structures and Routines
  2678. * Assumes that all rendering is done in a low resolution
  2679. * screen of 4 bitplanes depth.
  2680.  
  2681.  
  2682. * new line structure definition V2.0. Can be defined statically using
  2683. * DC.W or generated by your program as required. Note that this code
  2684. * allows multiple lines to be drawn one after the other, and even allows
  2685. * mixing of SING and normal lines if wanted as well as lines of different
  2686. * colours in sequence!
  2687.  
  2688.  
  2689.         rsreset
  2690.  
  2691. line_screen    rs.l    1        ;ptr to 1st screen bitplane
  2692.                     ;(assumes continuity)
  2693. line_ssize    rs.w    1        ;size of 1 bitplane in bytes
  2694. line_smod    rs.w    1        ;screen modulo
  2695. line_coords    rs.l    1        ;ptr to line coord list
  2696.  
  2697. ;workspace entries for drawline() routine
  2698.  
  2699. line_deltax    rs.w    1
  2700. line_deltay    rs.w    1
  2701. line_2S_L    rs.w    1
  2702. line_oct_bits    rs.b    1
  2703. line_pad        rs.b    1
  2704.  
  2705. line_sizeof    rs.w    0
  2706.  
  2707.  
  2708. * line coord list structure
  2709.  
  2710.  
  2711.         rsreset
  2712.  
  2713. lc_next        rs.l    1    ;=ptr to next coord list entry,
  2714.                 ;0 if last in list
  2715. lc_x1        rs.w    1
  2716. lc_y1        rs.w    1    ;coords of start point
  2717. lc_x2        rs.w    1
  2718. lc_y2        rs.w    1    ;coords of end point
  2719.  
  2720. lc_pattern    rs.w    1    ;should you want a dotted line...
  2721.  
  2722. lc_bits        rs.b    1    ;bitplanes & SING bit if wanted
  2723. lc_pad        rs.b    1    ;padding byte for alignment
  2724.  
  2725. lc_sizeof    rs.w    0
  2726.  
  2727. * lc_bits : 0-3 = colour (bitplanes in which drawn)
  2728. *     : 4 = SING bit for line draw
  2729.  
  2730.  
  2731.  
  2732. ;drawline(a4,a5) a4 = ptr to line structure definition V2.0
  2733. ;a5 = ptr to custom chip registers
  2734.  
  2735.  
  2736. ;draws line(s) according to the contents of the line definition
  2737. ;structure(s). Note : line definition structure is a header structure
  2738. ;containing workspace used by drawline() in this version. Actual
  2739. ;coordinate and bitplane information etc., contained in separate list
  2740. ;pointed to by an entry in the line definition structure.
  2741.  
  2742. ;Core algorithm from Amiga System Programmer's Guide. Several
  2743. ;addenda of my own for multiple bitplane handling, SING mode
  2744. ;drawing etc. (SING mode needed for polygon drawing prior to
  2745. ;polygon fill-see elsewhere for more info).
  2746.  
  2747. ;d0-d7/a0-a3 corrupted
  2748.  
  2749.  
  2750. drawline        move.l    line_coords(a4),a3
  2751.  
  2752. drawline_l0    moveq    #0,d1        ;clear line octant selector
  2753.         move.w    lc_x2(a3),d0
  2754.         sub.w    lc_x1(a3),d0    ;compute deltax = x2-x1
  2755.         roxl.w    #1,d1        ;condition octant selector
  2756.         tst.w    d0        ;>0 or <0?
  2757.         bge.s    drawline_b1    ;>=0 so skip
  2758.         neg.w    d0        ;else absolute value
  2759.  
  2760. drawline_b1    move.w    d0,line_deltax(a4)
  2761.         move.w    lc_y2(a3),d0
  2762.         sub.w    lc_y1(a3),d0    ;compute deltay = y2-y1
  2763.         roxl.w    #1,d1        ;condition octant selector
  2764.         tst.w    d0
  2765.         bge.s    drawline_b2
  2766.         neg.w    d0        ;absolute value again
  2767.  
  2768. drawline_b2    move.w    d0,line_deltay(a4)
  2769.  
  2770.         move.w    line_deltax(a4),d2
  2771.         move.w    d2,d3
  2772.         sub.w    d0,d3        ;want largest of Dx,Dy
  2773.  
  2774.         roxl.w    #1,d1        ;condition octant selector
  2775.         tst.w    d3
  2776.         bge.s    drawline_b3
  2777.         exg    d0,d2        ;ensure smallest of the
  2778.                     ;two in d0
  2779.  
  2780. ;From here on, DS = Delta S, DL = Delta L, as in the book. DS = smallest
  2781. ;of Dx, Dy, and DL = largest of Dx, Dy. I reuse the line_deltax(a4)
  2782. ;entries in the structure for these, simply changing the order in
  2783. ;which they appear if needed instead of having separate line_deltas()
  2784. ;and line_deltal() entries. Trivial really.
  2785.  
  2786. ;Some stuff is pre-calculated, and then saved in workspace entries
  2787. ;provided in the line definition structure for this purpose.
  2788.  
  2789. drawline_b3    movem.w    d0/d2,line_deltax(a4)    Dx = DS, Dy = DL
  2790.  
  2791.         lea    octants(pc),a0    ;ptr to octant selector table
  2792.         add.w    d1,a0
  2793.         clr.w    d1
  2794.         move.b    (a0),d1        ;get octant code
  2795.         move.b    lc_bits(a3),d0
  2796.         and.b    #$10,d0        ;get SING bit
  2797.         lsr.b    #3,d0
  2798.         or.b    d0,d1        ;put in eventual blitter
  2799.                     ;control bits
  2800.  
  2801.         asl.w    line_deltax(a4)        ;2*DS
  2802.         move.w    line_deltax(a4),d0
  2803.         sub.w    line_deltay(a4),d0    ;2*DS - DL
  2804.  
  2805.         bge.s    drawline_b4
  2806.         or.b    #$40,d1            ;set SIGN bit if needed
  2807.  
  2808. drawline_b4    move.b    d1,line_oct_bits(a4)    ;save BLTCON1 bits
  2809.                         ;for later
  2810.  
  2811.         move.w    d0,line_2S_L(a4)        ;save 2*DS-DL
  2812.  
  2813.         move.l    line_screen(a4),a0    ;screen pointer
  2814.  
  2815.         move.w    d0,d1
  2816.         sub.w    line_deltay(a4),d1    ;2*DS - 2*DL
  2817.         move.w    lc_y1(a3),d2
  2818.  
  2819.         mulu    line_smod(a4),d2        ;y1 * bitplane size
  2820.         move.w    lc_x1(a3),d3
  2821.         asr.w    #4,d3
  2822.         add.w    d3,d3            ;2*int(x1/16)
  2823.         ext.l    d3
  2824.         add.l    d3,d2            ;bitplane offset
  2825.  
  2826.         move.w    line_deltax(a4),d3    ;2*DS
  2827.  
  2828.         moveq    #0,d4
  2829.         move.w    lc_x1(a3),d4
  2830.         and.w    #$F,d4            ;frac(x1/16)
  2831.         ror.w    #4,d4            ;create STARTx bits
  2832.         move.w    d4,d5
  2833.         swap    d4
  2834.         move.w    d5,d4            ;copy to TEXTUREx bits
  2835.  
  2836.         or.b    line_oct_bits(a4),d4    ;create BLTCON1 bits
  2837.  
  2838.         swap    d4
  2839.         or.w    #$BCA,d4            ;create BLTCON0 bits
  2840.  
  2841.         swap    d4
  2842.         move.w    line_deltay(a4),d5    ;get DL
  2843.  
  2844.         moveq    #3,d7            ;no of bitplanes - 1
  2845.  
  2846.  
  2847. ;NB : trick here. Upper word of d7=0 after moveq #3,d7. Use this as
  2848. ;the bitplane bit number, doing an addq.w #1,d7 each time, and using
  2849. ;swap d7 to alternate between bitplane number counter & bitplane bit
  2850. ;position counter.
  2851.  
  2852.  
  2853. drawline_l1    swap    d7        ;get bitplane bit number
  2854.         move.w    d7,d6        ;ready for test
  2855.         addq.w    #1,d7        ;next bitplane number
  2856.         swap    d7        ;back to loop counter
  2857.         btst    d6,lc_bits(a3)    ;bitplane flag set?
  2858.         beq.s    drawline_a1    ;no-get next
  2859.  
  2860. drawline_b5    btst    #6,DMACONR(a5)    ;blitter ready?
  2861.         bne.s    drawline_b5
  2862.  
  2863.         move.l    a0,a1        ;bitplane pointer
  2864.         add.l    d2,a1        ;offset to 1st word of line
  2865.         move.w    d0,BLTAPTL(a5)    ;2*DS-DL
  2866.         move.w    d1,BLTAMOD(a5)    ;2*DS - 2*DL
  2867.         move.l    a1,BLTCPTH(a5)
  2868.         move.l    a1,BLTDPTH(a5)    ;bitplane pointers proper
  2869.         move.w    d3,BLTBMOD(a5)    ;2*DS
  2870.         move.l    #-1,BLTAFWM(a5)        ;set masks
  2871.         move.w    #$8000,BLTADAT(a5)    ;1 bit must be set
  2872.  
  2873.         move.w    line_smod(a4),BLTCMOD(a5)
  2874.         move.w    line_smod(a4),BLTDMOD(a5)    ;bitplane moduli!
  2875.  
  2876.         move.l    d4,BLTCON0(a5)    ;set blitter control regs!
  2877.  
  2878.         move.w    lc_pattern(a3),BLTBDAT(a5)    ;line pattern
  2879.  
  2880.         move.w    d5,d6
  2881.         lsl.w    #6,d6
  2882.         addq.w    #2,d6        ;BLTSIZE = 64*DL+2
  2883.  
  2884.         move.w    d6,BLTSIZE(a5)    ;draw line
  2885.  
  2886. drawline_a1    add.w    line_ssize(a4),a0        ;next bitplane pointer
  2887.  
  2888.         dbra    d7,drawline_l1
  2889.  
  2890.         move.l    lc_next(a3),d0    ;check if more lines to do
  2891.         beq.s    drawline_b6    ;none so exit
  2892.         move.l    d0,a3        ;else set pointer
  2893.         bra    drawline_l0    ;and do it
  2894.  
  2895. drawline_b6    rts
  2896.  
  2897.  
  2898. octants        dc.b    4*4+1
  2899.         dc.b    0*4+1
  2900.         dc.b    6*4+1
  2901.         dc.b    1*4+1
  2902.         dc.b    5*4+1
  2903.         dc.b    2*4+1
  2904.         dc.b    7*4+1
  2905.         dc.b    3*4+1
  2906.  
  2907.         even
  2908.  
  2909.  
  2910. Before documenting the boundary-fill mode of the blitter, some ideas for fut-
  2911. ure experimentation include : using different minterms as described in the
  2912. Amiga System Programmers' Guide, and tinkering directly with the SING bit to
  2913. examine its effects. Also, the SIGN bit's effects can be examined, and the
  2914. effect of using values other than $8000 in BLTADAT. I have not tried all of
  2915. these, so exercise care. Some of the result could be very interesting assum-
  2916. ing that the Amiga doesn't conk out under the strain...
  2917.  
  2918.     Boundary-filling:the blitter has a boundary-fill mode which makes
  2919. the construction of filled polygons quite simple, once the vagaries of which
  2920. registers have which values are dealt with.
  2921.  
  2922.     The blitter's boundary-fill operation is very simple-minded. When it
  2923. fills a boundary, it recognises the boundary by virtue of the existence of a
  2924. single pixel marking the boundary. Once it has found that single pixel, the
  2925. blitter fills all blank pixels until it encounters another single pixel mark-
  2926. ing the end of the boundary. More correctly, it uses the value of the FCI bit
  2927. (the Fill Carry In bit) of BLTCON1 to determine what the value of filled pix-
  2928. els should be.
  2929.  
  2930.     The algorithm is as follows:while a pixel equals zero, that pixel is
  2931. replaced by the value of the FCI bit. Initially for normal fills, this is set
  2932. to zero, ensuring that the initial fill leaves blank space around the bound-
  2933. ary. Once a set pixel is encountered, it inverts the FCI bit, and then uses
  2934. the ECE/ICE bits to determine what happens next. If the ICE bit (inclusive
  2935. carry enable) bit is set, the pixel is set to the new value of FCI AFTER the
  2936. inversion. If the ECE (exclusive carry enable) bit is set, the pixel is set
  2937. to the value of the FCI bit BEFORE the inversion. With ECE set, it is possi-
  2938. ble to obtain filled polygons with single-pixel corners, whereas corners of
  2939. filled polygons using ICE will always have at least two pixels at any corner
  2940. formed by the intersection of two boundary lines forming a peak (such as the
  2941. apex of a triangle). This makes most sense when I mention that the blitter
  2942. fills horizontally from right to left, a word at a time, until it has exhaus-
  2943. ted the row, and then moves on to the next row. Note also that if during the
  2944. fill of one raster line of pixels, it fails to encounter a boundary pixel,
  2945. the blitter will continue the fill on the next raster line until encounter-
  2946. ing a boundary pixel, resulting in weird and wonderful (but not always desi-
  2947. rable!) effects.
  2948.  
  2949.     Furthermore, the algorithm works only in DESCENDING mode, so that
  2950. the blitter's DESC bit must be set.
  2951.  
  2952.     So, to fill a boundary, the procedure is as follows:draw the poly-
  2953. gon boundary using the SING mode of the blitter's line-drawing function, so
  2954. that any lines with a slope of less than 45 degrees have only one pixel per
  2955. horizontal raster line. Having drawn the closed boundary in a suitable mem-
  2956. ory buffer, point the BLTxPTH/L registers at the END of the memory buffer,
  2957. and activate the blitter fill. This is fast-16 million pixels per second peak
  2958. speed.
  2959.  
  2960.     To illustrate the procedure best of all, I present a piece of code
  2961. that performs this function. This code can be freely ripped out of this DOC
  2962. file and mutilated ad lib to suit the programmer's personal prejudices (note
  2963. the use of alliteration! I passed my English Language O-Level! HAH! So what
  2964. I hear you say...)
  2965.  
  2966.     This code uses the line drawing code above to draw the boundary in
  2967. a memory buffer, then fills the buffer before transferring the contents of
  2968. the buffer to the screen. It uses a data structure, which I also include in
  2969. this section, to manage the polygon. Note that I refer to something called
  2970. the Laurence trick for managing the blitter. This refers to a trick devised
  2971. by a colleague of mine, a Belgian programmer called Laurence Vanhelsuwe who
  2972. first used the trick of setting the modulo to -2 for blitter data block move-
  2973. ments. I refer to it frequently in my blitter routines.
  2974.  
  2975.  
  2976. * polygon definition structure. See draw_polygon() routine
  2977. * for more info.
  2978.  
  2979.  
  2980.         rsreset
  2981.  
  2982. poly_screen    rs.l    1    ;1st bitplane to draw polygon on
  2983. poly_ssize    rs.w    1    ;bitplane size
  2984. poly_smod    rs.w    1    ;bitplane width in bytes
  2985.  
  2986. poly_buffer    rs.l    1    ;where to draw polygon before rendering
  2987.                 ;on the real screen...
  2988. poly_wide    rs.w    1    ;width of buffer in words
  2989. poly_tall    rs.w    1    ;height in raster lines
  2990.  
  2991. poly_border    rs.l    1    ;pointer to line definition structure
  2992.  
  2993. poly_xpos    rs.w    1    ;position to plot finished polygon
  2994. poly_ypos    rs.w    1    ;on the screen
  2995.  
  2996. poly_flag    rs.b    1    ;colours
  2997. poly_pad        rs.b    1
  2998.  
  2999. poly_sizeof    rs.w    0
  3000.  
  3001.  
  3002. * poly_flag    : bits 0-3 = colour
  3003.  
  3004.  
  3005. * poly_border : points to line definition structure. This in turn has
  3006. * a pointer to a line coord list, each entry of which should have the
  3007. * SING bit set in lc_bits.
  3008.  
  3009.  
  3010. ;draw_polygon(a4,a5)
  3011.  
  3012. ;a4 = ptr to polygon structure definition block
  3013. ;a5 = ptr to custom chip registers
  3014.  
  3015. ;creates polygon using blitter line draw in SING mode into a buffer
  3016. ;followed by blitter fill. Then transfers the whole lot to the screen
  3017. ;at the desired polygon coordinates. I.e. pre-plots in buffer. Only
  3018. ;pre-plots in one bitplane, for max efficiency, then moves the entire
  3019. ;lot over to the actual screen, copying only to those bitplanes
  3020. ;required. Obviously, if plotting in colour 9 over a background with
  3021. ;pixel data in colours 2 & 6, these will show up as colour 11 & 15
  3022. ;pixel data (for a 4-bitplane screen).
  3023.  
  3024. ;note:for optimum efficiency of memory usage, define your polygon
  3025. ;with one corner at (0,0) or as close as possible to it.
  3026.  
  3027. ;d0-d7/a0-a3 corrupt
  3028.  
  3029.  
  3030. draw_polygon    move.l    poly_border(a4),a3
  3031.  
  3032.         move.l    line_coords(a3),d0    ;get coord list
  3033.         beq    draw_poly_done        ;doesn't exist-BYE!
  3034.         move.l    d0,a3
  3035.  
  3036.         moveq    #0,d0        ;potential x & y coord
  3037.         moveq    #0,d1        ;maxima
  3038.  
  3039. draw_poly_l1    move.w    lc_x1(a3),d2
  3040.         move.w    lc_y1(a3),d3
  3041.         cmp.w    d2,d0
  3042.         bge.s    draw_poly_b1
  3043.         move.w    d2,d0        ;new x maximum
  3044. draw_poly_b1    cmp.w    d3,d1
  3045.         bge.s    draw_poly_b2
  3046.         move.w    d3,d1        ;new y maximum
  3047. draw_poly_b2    move.w    lc_x2(a3),d2
  3048.         move.w    lc_y2(a3),d3
  3049.         cmp.w    d2,d0
  3050.         bge.s    draw_poly_b3
  3051.         move.w    d2,d0        ;new x maximum
  3052. draw_poly_b3    cmp.w    d3,d1
  3053.         bge.s    draw_poly_b4
  3054.         move.w    d3,d1        ;new y maximum
  3055.  
  3056. draw_poly_b4    move.l    lc_next(a3),a3    ;find next set of coords
  3057.         move.l    a3,d2        ;check if they exist
  3058.         bne.s    draw_poly_l1    ;yes, back for more testing
  3059.  
  3060. ;this for debug only
  3061.  
  3062.         move.w    d0,debug
  3063.         move.w    d1,debug+2
  3064.  
  3065. ;Use max x&y coord values to determine size of buffer to clear
  3066. ;using the blitter.
  3067.  
  3068.         move.w    d0,d2
  3069.         lsr.w    #4,d0        ;int(max_x/16) = word count
  3070.         and.w    #%1111,d2    ;check fraction
  3071.         beq.s    draw_poly_b5
  3072.         addq.w    #1,d0        ;1 word more
  3073.  
  3074. draw_poly_b5    move.w    d0,poly_wide(a4)    ;WORD count!
  3075.         move.w    d1,poly_tall(a4)    ;height in raster lines
  3076.  
  3077.  
  3078. ;prepare to clear buffer in which polygon is to be drawn.
  3079. ;Clear using blitter - it's most efficient!
  3080.  
  3081.         move.w    d1,d6
  3082.         lsl.w    #6,d6
  3083.         add.w    d0,d6        ;this is BLTSIZE
  3084.  
  3085.         move.w    d6,debug+4
  3086.         clr.w    debug+6
  3087.  
  3088.         move.w    #$01F0,BLTCON0(a5)    ;USED only
  3089.                         ;minterms $F0
  3090.         clr.w    BLTCON1(a5)        ;normal mode, no shift
  3091.  
  3092.         move.l    poly_buffer(a4),BLTDPTH(a5)    ;ptr to buffer
  3093.                             ;to clear
  3094.  
  3095.         clr.w    BLTDMOD(a5)    ;D modulo zero
  3096.         clr.w    BLTADAT(a5)    ;A data zero for clear
  3097.         moveq    #-1,d2
  3098.         move.l    d2,BLTAFWM(a5)    ;ensure masks allow data passage
  3099.         move.w    d6,BLTSIZE(a5)    ;and clear buffer!
  3100.  
  3101.         move.l    poly_border(a4),a3    ;ptr to coord
  3102.                         ;struct for border
  3103.  
  3104.         add.w    d0,d0        ;WORD count to BYTE count
  3105.         move.w    d0,line_smod(a3)
  3106.         mulu    d0,d1        ;size of buffer in bytes
  3107.         move.w    d1,line_ssize(a3)    ;won't be a long really!
  3108.  
  3109.         move.l    poly_buffer(a4),d2
  3110.         move.l    d2,line_screen(a3)
  3111.  
  3112.         move.l    a4,-(sp)
  3113.         move.l    a3,a4        ;point to line structure
  3114.  
  3115.         bsr    drawline        ;& draw the lines
  3116.  
  3117.         move.l    (sp)+,a4        ;recover pointer
  3118.  
  3119.  
  3120. ;now activate blitter fill. Note : that works only if descending mode
  3121. ;selected. This code does that. This is an exclusive fill enable type
  3122. ;fill, with FCI initially zero (non-inverting fill).
  3123.  
  3124.  
  3125. draw_poly_b6    btst    #6,DMACONR(a5)    ;wait till blitter done
  3126.         bne.s    draw_poly_b6    ;busy wait (sigh)
  3127.  
  3128.         move.l    poly_buffer(a4),a0    ;where border is
  3129.         move.w    poly_wide(a4),d1        ;width in words
  3130.         move.w    d1,d2
  3131.         move.w    poly_tall(a4),d3
  3132.         mulu    d3,d1            ;area size in words
  3133.         add.l    d1,d1            ;area size in bytes
  3134.         add.l    d1,a0            ;descending mode-
  3135.                         ;adjust pointer
  3136.         subq.l    #2,a0            ;point to last word
  3137.                         ;of data proper!
  3138.         move.l    a0,BLTDPTH(a5)
  3139.         move.l    a0,BLTAPTH(a5)        ;two pointers
  3140.         clr.w    BLTAMOD(a5)
  3141.         clr.w    BLTDMOD(a5)        ;both moduli zero!
  3142.         moveq    #-1,d0
  3143.         move.l    d0,BLTAFWM(a5)        ;ensure masks OK
  3144.         move.w    #$09f0,BLTCON0(a5)    ;USEA/D, minterms $F0
  3145. ;        move.w    #$0012,BLTCON1(a5)    ;EFE on, FCI=0, DESC=1
  3146.         move.w    #$000A,BLTCON1(a5)    ;IFE on, FCI=0, DESC=1
  3147.         move.w    d3,d0            ;height
  3148.         lsl.w    #6,d0            ;*64
  3149.         add.w    d2,d0            ;add on width in words
  3150.         move.w    d0,BLTSIZE(a5)        ;start blitter
  3151.  
  3152.  
  3153. ;NB : when computing pointers for data blocks in above section,
  3154. ;use subq.l #2,a0 to point to last words proper, instead of beyond
  3155. ;the data blocks, otherwise the fill gets confused! Weird things
  3156. ;happen if you don't do this!
  3157.  
  3158.         
  3159.         move.l    poly_screen(a4),a0    ;screen pointer
  3160.         move.l    poly_buffer(a4),a2    ;ptr to polygon buffer
  3161.         moveq    #0,d0
  3162.         move.w    #BP_BYTES,d5    ;no of bytes per screen bitplane
  3163.  
  3164.         move.w    poly_ypos(a4),d0
  3165.         mulu    poly_smod(a4),d0    ;y coordinate * screen modulo
  3166.         add.l    d0,a0
  3167.         move.w    poly_xpos(a4),d0
  3168.         move.w    d0,d4            ;save x coordinate
  3169.         lsr.w    #4,d0            ;2*int(x/16)
  3170.         add.w    d0,d0
  3171.         add.w    d0,a0            ;now this is initial pointer
  3172.  
  3173.         move.w    poly_smod(a4),d2    ;screen modulo
  3174.         move.w    poly_wide(a4),d3
  3175.  
  3176.         addq.w    #1,d3        ;word cols + 1:Laurence trick
  3177.         add.w    d3,d3        ;Part 2
  3178.         sub.w    d3,d2
  3179.         move.w    d2,d0        ;C,D mods in d0
  3180.         swap    d0
  3181.         move.w    #-2,d0        ;A,B mods also
  3182.  
  3183.         moveq    #-1,d1        ;blitter mask values:Laurence
  3184.         clr.w    d1        ;Trick Part 3
  3185.  
  3186.         move.w    d4,d2        ;get x coordinate
  3187.         and.w    #%1111,d2    ;frac(x/16)
  3188.         ror.w    #4,d2        ;put in top 4 bits for BLTCONx
  3189.         move.w    d2,d3
  3190.         or.w    #$0FCA,d2    ;USEA/B/C/D, minterms $CA
  3191.         swap    d2
  3192.         move.w    d3,d2        ;create BLTCONx bits
  3193.  
  3194.         moveq    #0,d3
  3195.         move.w    poly_tall(a4),d3
  3196.         and.w    #$3FF,d3
  3197.         lsl.w    #6,d3
  3198.         move.w    poly_wide(a4),d6
  3199.         addq.w    #1,d6
  3200.         and.w    #$3f,d6
  3201.         add.w    d6,d3        ;this is BLTSIZE!!
  3202.  
  3203.         moveq    #3,d7        ;no of bitplanes
  3204.  
  3205. ;here transfer polygon to screen bitplanes according to colour
  3206. ;specifier. a0 = ptr to screen location, d0 = moduli (C,D high
  3207. ;word, A,B low word), d1 = blitter mask values, d2 = BLTCON0
  3208. ;and BLTCON1 control words, d5 = size of 1 screen bitplane in
  3209. ;bytes, d3 = BLTSIZE value pre-calculated (will stay the same
  3210. ;size throughout the operation) and a2 = ptr to polygon buffer.
  3211. ;So leave d0-d5/a0/a2 alone while within the loop!. Leave a4 alone
  3212. ;anyway or the routine will crash! Freely alter d6/a1/a3. This
  3213. ;info in case you have any flash refinements to make. Note one of my
  3214. ;favourite tricks-using SWAP & sticking counters/other data in both
  3215. ;words of 1 reg.
  3216.  
  3217. ;Note that the choice of sources A and B dosen't matter here because
  3218. ;they're both the same! If you use different sources, remember to
  3219. ;make Source A the MASK, Source B the DATA, Source C the BACKGROUND!
  3220.  
  3221.  
  3222. draw_poly_l2    swap    d7            ;bitplane bit no
  3223.         move.w    d7,d6            ;copy
  3224.         addq.w    #1,d7            ;next bitplane no
  3225.         swap    d7            ;back to counter
  3226.         btst    d6,poly_flag(a4)    ;this bitplane?
  3227.         beq    draw_poly_b8
  3228.  
  3229. draw_poly_b7    btst    #6,DMACONR(a5)    ;wait till blitter done
  3230.         bne.s    draw_poly_b7    ;busy wait (sigh)
  3231.  
  3232.         move.l    a0,BLTDPTH(a5)    ;ptr to screen area to plot to
  3233.         move.l    a0,BLTCPTH(a5)
  3234.         move.l    a2,BLTAPTH(a5)    ;ptr to polygon buffer
  3235.         move.l    a2,BLTBPTH(a5)
  3236.  
  3237.         move.w    d0,BLTAMOD(a5)    ;A,B  moduli -2:Laurence trick
  3238.         move.w    d0,BLTBMOD(a5)    ;Part 1
  3239.         swap    d0        ;get C,D moduli
  3240.         move.w    d0,BLTDMOD(a5)    ;C,D moduli
  3241.         move.w    d0,BLTCMOD(a5)
  3242.         swap    d0        ;recover A,B moduli again
  3243.  
  3244.         move.l    d1,BLTAFWM(a5)    ;blitter masks (see above)
  3245.         move.l    d2,BLTCON0(a5)
  3246.  
  3247.         move.w    d3,BLTSIZE(a5)    ;start blitter
  3248.  
  3249. draw_poly_b8    add.w    d5,a0        ;next bitplane
  3250.  
  3251.         dbra    d7,draw_poly_l2    ;continue
  3252.         
  3253. draw_poly_done    rts
  3254.  
  3255.  
  3256. Hardware:Sound Management
  3257.  
  3258.  
  3259. For those who like the Jean-Michel Jarre sound effects that the Amiga is able
  3260. to reproduce (guess who's bought all of his albums!) and wish to reproduce a
  3261. similar gee-whizz set of sound effects, this is the section for you.
  3262.  
  3263.     However, I warn anyone who hasn't studied maths to a decent level of
  3264. the horrors to come. Sound synthesis using the additive method of the Paula
  3265. chip is best understood by those who know something about Fourier analysis! I
  3266. shall try to make this as painless as possible.
  3267.  
  3268.     All sound waves, plotted graphically, are formed from lots of sine
  3269. (and/or cosine) curves added together. The fun part about adding sine and co-
  3270. sine functions together is that you get a more complex waveform as a result.
  3271. This is known by the lofty title of the principle of superposition of wave-
  3272. forms. So any waveform can be broken down into components of the form
  3273.  
  3274.  
  3275.         A * sin ((n * x) + p))
  3276.  
  3277.  
  3278. where A is the amplitude of the component (which equates approximately to the
  3279. volume), n is a constant multiplier from 1 onwards, and p is the phase angle.
  3280. The phase angle describes how far along the x-axis the curve is shifted. As
  3281. it happens to be true that cos(x) = sin(x+w) where w=90 degrees or pi/2 rad-
  3282. ians, all components of a sound wave can be represented as above.
  3283.  
  3284.     As an exercise, to see this in action, try plotting a graph of the
  3285. function
  3286.  
  3287.  
  3288.         sin(x) - (1/3)sin(3x) + (1/5)sin(5x) - ...
  3289.  
  3290.  
  3291. for as many terms as you can bother to calculate. You'll find the waveform is
  3292. interesting.
  3293.  
  3294.     This leads directly on to some musical definitions, and their rela-
  3295. ted mathematical definitions. The amplitude of the curve, namely the distance
  3296. between the highest peak and the lowest trough of the curve, defines the vol-
  3297. ume of the sound. The pitch is related to the frequency, which in turn is in
  3298. direct relation to the constant n in the first expression above. Where one of
  3299. the components of the curve has a large constant multiplier in front of it,
  3300. i.e., the value of A is large, that component is the dominant one and defines
  3301. the pitch of the note. This is the principal note. The lesser components are
  3302. known as the harmonics, especially when they are in some numeric relation to
  3303. the principal note. In the second expression above, the second and third com-
  3304. ponents define harmonics for the note, the principal is the term sin(x), and
  3305. the amplitude of the whole is the distance between the peaks & troughs, which
  3306. for this waveform should be 2*(1-1/3+1/5-...). Anyone now worrying about the
  3307. amplitude of this being infinite, because of it being an infinite series, be
  3308. reassured. The series may be infinite, but for good mathematical reasons it
  3309. ends up as a finite value! Trust me-I did this at university!
  3310.  
  3311.     Anyone wishing to construct a waveform using this idea, be warned.
  3312. The ultimate result of embarking on this course is to immerse oneself in the
  3313. varagries of Fourier analysis, so called because Joseph Fourier, the French
  3314. mahtematician, first published a treatise on the subject (which he became in-
  3315. terested in precisely because he wished to analyse music mathematically). If
  3316. you carry this through, you'll find yourself immersed in masses of trigono-
  3317. metrical integration and orthogonality computations, and if you don't know
  3318. what that means, you're best avoiding this method!
  3319.  
  3320.     Fortunately, there are other ways of creating your waveform. One can
  3321. simply draw a nice-looking graph of what looks like a waveform, and instead
  3322. of working out the x,y values the hard way as above, simply read them off the
  3323. graph. It is these values that Paula uses!
  3324.  
  3325.     Now, it is time to discuss other effects. The frequency of the wave
  3326. need not be constant. Varying the frequency rapidly about the principal note
  3327. by a small amount creates vibrato. Slowing the rate of variation gives rise
  3328. to tremolo. The shape of the curve above defines a quality called timbre, and
  3329. this is the reason that so many musical instruments sound differently even if
  3330. they all play the same note. Their sounds, when taken via a microphone, sent
  3331. through an amplifier and displayed on an oscilloscope screen, give rise to a
  3332. whole variety of different curve shapes. It was these shapes that led Fourier
  3333. to perform his mathematics which describes them. And yes, Paula can reproduce
  3334. all of these! By way of example, a square wave has the equation
  3335.  
  3336.  
  3337.     y = sin(x) + (1/3)sin(3x) + (1/5)sin(5x) + ...
  3338.  
  3339.  
  3340. which is slightly different to the first example. A sawtooth wave has the
  3341. equation
  3342.  
  3343.  
  3344.     y = sin(x) + (1/2)sin(2x) + (1/3)sin(3x) + ...
  3345.  
  3346.  
  3347. and for your education, anyone with a Yamaha DX7 synthesiser will know that
  3348. this instrument builds its sounds in precisely this way (which is why it is
  3349. so hard to play one!).
  3350.  
  3351.     Noise, as opposed to music, is defined as randomly superposed fre-
  3352. quencies. White noise, as it is called, is a mathematical idealisation that
  3353. is impossible to achieve in practice, and consists of all possible frequen-
  3354. cies superposed one upon another. Pink noise is a more limited selection of
  3355. such frequencies played simultaneously, and good pink noise generators are
  3356. capable of generating all audible frequencies simultaneously, thus provid-
  3357. ing a good approximation to white noise. Noise curves, when plotted, look
  3358. like the paths described by spiders walking after immersion in vodka. Anyone
  3359. who has seen sound traces on oscilloscopes will know what I mean.
  3360.  
  3361.     Having finished the preamble, it is now time to consider how to im-
  3362. plement this on Paula. First, let us look at the register list for Paula:
  3363.  
  3364.  
  3365.     Offset    Name    Function
  3366.     ------    ----    --------
  3367.     ADKCON    09E    Audio & Disc Controller
  3368.             (Cross-reference #5)
  3369.  
  3370.     AUD0LCH    0A0    High word, audio data address, channel 0
  3371.     AUD0LCL    0A2    Low word, audio data address, channel 0
  3372.     AUD0LEN    0A4    Data length, channel 0
  3373.     AUD0PER    0A6    Period duration, channel 0
  3374.     AUD0VOL    0A8    Volume, channel 0
  3375.     AUD0DAT    0AA    Audio data, channel 0 (to D/A converter)
  3376.  
  3377.     AUD1LCH    0B0    High word, audio data address, channel 0
  3378.     AUD1LCL    0B2    Low word, audio data address, channel 0
  3379.     AUD1LEN    0B4    Data length, channel 0
  3380.     AUD1PER    0B6    Period duration, channel 0
  3381.     AUD1VOL    0B8    Volume, channel 0
  3382.     AUD1DAT    0BA    Audio data, channel 0 (to D/A converter)
  3383.  
  3384.     AUD2LCH    0C0    High word, audio data address, channel 0
  3385.     AUD2LCL    0C2    Low word, audio data address, channel 0
  3386.     AUD2LEN    0C4    Data length, channel 0
  3387.     AUD2PER    0C6    Period duration, channel 0
  3388.     AUD2VOL    0C8    Volume, channel 0
  3389.     AUD2DAT    0CA    Audio data, channel 0 (to D/A converter)
  3390.  
  3391.     AUD3LCH    0D0    High word, audio data address, channel 0
  3392.     AUD3LCL    0D2    Low word, audio data address, channel 0
  3393.     AUD3LEN    0D4    Data length, channel 0
  3394.     AUD3PER    0D6    Period duration, channel 0
  3395.     AUD3VOL    0D8    Volume, channel 0
  3396.     AUD3DAT    0DA    Audio data, channel 0 (to D/A converter)
  3397.  
  3398.  
  3399. Complications arise because ADKCON controls the disc and UART as well as the
  3400. sound output. However, ADKCON works on the SETIT principle in an identical
  3401. fashion to DMACON and other like control registers, so that the programmer
  3402. can choose to set only those bits pertinent to the sound system. Only the low
  3403. 8 bits are used for sound, and bit 15 acts as the SETIT bit (#5) as for DMA-
  3404. CON. The bit assignments for sound are:
  3405.  
  3406.  
  3407.     Bit    Name    Function
  3408.     ---    ----    --------
  3409.     15    SETIT    see DMACON
  3410.     7    USE3PN    Audio channel 3 modulates nothing
  3411.     6    USE2P3    Channel 2 modulates period of channel 3
  3412.     5    USE1P2    Channel 1 modulates period of channel 2
  3413.     4    USE0P1    Channel 0 modulates period of channel 1
  3414.     3    USE3VN    Channel 3 modulates nothing
  3415.     2    USE2V3    Channel 2 modulates volume of channel 3
  3416.     1    USE1V2    Channel 1 modulates volume of channel 2
  3417.     0    USE0V1    Channel 0 modulates volume of channel 1
  3418.  
  3419.  
  3420. These usages will be explained later.
  3421.  
  3422.     There exist two possible ways of creating a sound. First, one could
  3423. draw a graph of one wave of the waveform, digitise it (i.e., read off the y
  3424. values at equally spaced x intervals, and rescale these y values to that they
  3425. lie within the range -127 to +127) and put the data into CHIP RAM. Then, set
  3426. Paula up to play the waveform, and write a piece of interrupt code to respond
  3427. to an audio interrupt by replaying the waveform repeatedly. This limits the
  3428. note to one waveform, but the pitch can be varied within the interrupt code.
  3429.  
  3430.     The second method is to digitise an ENTIRE sound into CHIP RAM, and
  3431. set Paula up to play the whole lot in one go. This is obviously a task that
  3432. is not suited to hand-calculation, and to assist with this, special digitiser
  3433. hardware exists that can be interfaced to the Amiga to perform this function,
  3434. this hardware being known as a SAMPLER. By using a sampler, an entire single
  3435. record can, in theory, be digitised and played on the Amiga (for an example
  3436. of what is capable, listen to the Xenon 2 Megablast soundtrack by Bomb The
  3437. Bass!).
  3438.  
  3439.     Problems occur because of the use of 8-bit data resolution within
  3440. the sound system. A certain quality can be achieved, but for comparison, a
  3441. compact disc player uses 16 bits for hi-fi quality. So anyone toying with the
  3442. idea of reproducing studio quality classical music on the Amiga directly will
  3443. possibly be disappointed-there may be a noticeable change in quality. Because
  3444. all analogue to digital conversion involves sampling errors, due to the roun-
  3445. ding effect of A/D conversion, a quantity called the quantization error res-
  3446. ults. For an 8-bit system, the maximum possible quantization error is 1/256
  3447. of the digitised value. The magnitude of the quantization error is directly
  3448. proportional to a noise value called the quantization noise, which may have a
  3449. deleterious effect upon sound quality (hence the use of 16 bits by CD players
  3450. which reduces the quantization error to 1/65536 of the digitised value).
  3451.  
  3452.     Now, the first quantity that requires calculation is the sampling
  3453. rate. This is the rate at which the sampler 'snapshots' the analogue sound
  3454. data and converts it into digital data. If the data is not sent to Paula at
  3455. the same rate, then the sound will be shifted in frequency with the possi-
  3456. bility of distortion occurring (but of course, there is no reason why this
  3457. cannot be done deliberately for special effects!).
  3458.  
  3459.     If using one waveform, the number of samples per waveform is equal
  3460. to the number of y values you have decided to use. To make sine curves con-
  3461. form more closely to the ideal, increase the number of samples.
  3462.  
  3463.     A simple example illustrates this. Let us reproduce a pure tone, as
  3464. represented by a pure sine wave. One complete wave consists of the curve from
  3465. 0 degrees to 360 degrees. Let us split this up into 16 samples. So we require
  3466. the values of sin(x) from 0 to 360 degrees in 16 steps, scaled so that the
  3467. end results lie within the range -127 to +127. Because sin(x) varies from -1
  3468. to +1, we therefore want the values of 127*sin(x) over this range. The values
  3469. thus required are:
  3470.  
  3471.  
  3472.             0
  3473.             48.6007
  3474.             89.8025
  3475.             117.3327
  3476.             127
  3477.             117.3327
  3478.             89.8025
  3479.             48.6007
  3480.             0
  3481.             -48.6007
  3482.             -89.8025
  3483.             -117.3327
  3484.             -127
  3485.             -117.3327
  3486.             -89.8025
  3487.             -48.6007
  3488.  
  3489.  
  3490. Rounding these to the nearest whole number (which introduces the quantization
  3491. error unfortunately, and cannot be avoided because Paula can't handle float-
  3492. ing point numbers!) and putting this list of bytes into CHIP RAM, yields the
  3493. desired sample data. Since Paula uses standard twos-complement bytes, and it
  3494. is usual for assemblers to generate these directly from negative numbers, we
  3495. can insert these values directly into a DC.B list, e.g.;
  3496.  
  3497.  
  3498. sine_wave    dc.b    0,49,90,117
  3499.         dc.b    127,117,90,49
  3500.         dc.b    0,-49,-90,-117
  3501.         dc.b    -127,-117,-90,-49
  3502.  
  3503.  
  3504.     Now, we point Paula's data registers at the start of the list. This
  3505. is usually done using something like
  3506.  
  3507.  
  3508.         LEA    $DFF000,A5
  3509.         LEA    sine_wave(PC),A0
  3510.         MOVE.L    A0,AUD0LCH(A5)
  3511.  
  3512.  
  3513. Now we tell Paula how long the sample list is in WORDS. There are 16 actual
  3514. data bytes. The value to write to AUD0LEN is thus 16/2 = 8. For lists with
  3515. an odd number of bytes, e.g., 17 instead of 16, use 17/2 rounded DOWN to the
  3516. nearest integer, i.e., 8 again. Use the instruction:
  3517.  
  3518.  
  3519.         MOVE.W    #8,AUD0LEN(A5)
  3520.  
  3521.  
  3522. to set the list length. For longer lists, use two labels, one at the start of
  3523. the list, one at the end of the list, and use something like
  3524.  
  3525.  
  3526.         MOVE.W    #(end-start)/2,AUD0LEN(A5)
  3527.  
  3528.  
  3529. (as in the Amiga Systems Programmer's Guide).
  3530.  
  3531.     Now we select the output volume. Since this is going to be a cons-
  3532. tant value, and we can choose any value from 0 to 64, let us choose half of
  3533. full volume:
  3534.  
  3535.  
  3536.         MOVE.W    #32,AUD0VOL(A5)
  3537.  
  3538.  
  3539. Now we need to choose our sampling rate. In this case, the sampling rate will
  3540. affect the frequency of the sound. So we can use the relation
  3541.  
  3542.  
  3543.         F = S/N
  3544.  
  3545.  
  3546. where F is the frequency, S is the sampling rate, and N is the number of sam-
  3547. ples per cycle. In this case, N=16. Now we cannot specify the frequency as a
  3548. specific number of Hertz, but need to relate it to the number of bus cycles.
  3549. A bus cycle is 279.365 nanoseconds. We need to compute the sample period as
  3550. given by the relation
  3551.  
  3552.  
  3553.         P = 1/(S * 2.79365 * 10E-7)
  3554.  
  3555.  
  3556. where I use 10E-7 to represent 10 to the power of -7. To play our sine wave
  3557. at International A, or 440 Hz, we need to transform our frequency relation,
  3558. and yield
  3559.  
  3560.  
  3561.         S = F * N
  3562.  
  3563.  
  3564. Using F=440, N=16, we have S = 7040 Hz. Now this will give P as the value
  3565.  
  3566.  
  3567.         1/(7040 * 2.79365 * 10E-7)
  3568.  
  3569.  
  3570. or 508.4583. Rounding, this yields 508. We therefore set up Paula using
  3571.  
  3572.  
  3573.         MOVE.W    #508,AUD0PER(A5)
  3574.  
  3575.  
  3576. to generate the appropriate International A note. The resulting note will in
  3577. actuality deviate by 0.4 Hz from the true value, but only a listener posses-
  3578. sing perfect pitch (particularly a classical musician) will notice the diff-
  3579. erence.
  3580.  
  3581.     There exists some limit upon the AUDxPER values. Each audio channel
  3582. has one DMA slot per raster line, and hence one word, or two samples, can be
  3583. read in one raster line. Thus the smallest possible value for the sampling
  3584. period is 114 (NOT 124 as given in the Amiga Systems Programmer's Gude!). The
  3585. value is obtained as follows:one raster line equals 63.5 microseconds. So one
  3586. second contains 1/(63.5 * 10E-6) raster lines, which rounded up equals 15748
  3587. raster lines. Two samples can be read per raster line, or 31496 samples when
  3588. read at maximum speed. This yields P = 113.65, or rounded up, 114. Selecting
  3589. a value lower than 114 will result in some data words being output twice, as
  3590. the DMA system cannot fetch the next data word on time. This gives a sampling
  3591. rate of 1/(114 * 2.79356 * 10E-7) or 31399 Hz. Obviously, one can sample at a
  3592. slower rate, and even sample using P=65535 for weird effects!
  3593.  
  3594.     Having set up the registers, we need to activate the audio DMA. The
  3595. instruction
  3596.  
  3597.  
  3598.         MOVE.W    #$8201,DMACON(A5)
  3599.  
  3600.  
  3601. performs this (it sets AUD0EN and DMAEN just to be sure).
  3602.  
  3603.     At this point, Paula will play the sound. The example above will be
  3604. heard as a single note playing continuously, and eventually you will become
  3605. so sick of hearing it you'll turn the volume off on your monitor! This exam-
  3606. ple sounds like the horrible 'beep' accompanying the BBC test card...
  3607.  
  3608.     Now for some details. Paula has internal registers for data fetching
  3609. unlike the blitter (why the hell couldn't the blitter have them?), and when
  3610. Paula is started up, the AUDxLCH/L register pair contents are copied to these
  3611. internal registers before data fetching. Thus the initial values of AUDxLCH/L
  3612. are preserved. The same is true for AUDxLEN, AUDxVOL and AUDxPER (otherwise
  3613. you wouldn't hear the same 'beep' all the time when playing the example sound
  3614. above!). Only when the audio DMA is turned off will the sound stop!
  3615.  
  3616.     Now since the AUDxCLH/L values, etc, are copied to internal regis-
  3617. ters while playing, the processor can supply new values to change the note on
  3618. a continual basis. Uninterrupted sound generation can thus continue.
  3619.  
  3620.     Paula generates an interrupt at the end of each complete sound out-
  3621. put cycle. By enabling the audio interrupt bits, and linking in an interrupt
  3622. handler to the audio interrupt vector (IPL4) it is possible to change which
  3623. note is played under interrupt control. Be warned that for high frequencies
  3624. the interrupt occurs VERY OFTEN and if your interrupt code cannot respond to
  3625. it fast enough, the supervisor stack will overflow with unsatisfied inter-
  3626. rupt requests and crash the machine!
  3627.  
  3628.     As for all interrupt code, the interrupt handler must clear the
  3629. INTREQ bit for the appropriate channel after checking which channel caused
  3630. the interrupt to occur, and then perform whatever function the user desires,
  3631. be it changing the frequency of a note such as played in the above example,
  3632. or performing more complex changes such as switching between waveforms.
  3633.  
  3634.     Modulation:the term modulation is used to describe the process by
  3635. which one waveform can be used to change the output from another. Normally
  3636. two quantities are subject to modulation, volume and frequency.
  3637.  
  3638.     When a waveform A is used to alter the volume at which waveform B is
  3639. output, waveform A is described as a VOLUME ENVELOPE. When the waveform A is
  3640. used to alter the pitch of the notes played, waveform A is then described as
  3641. a TONE ENVELOPE.
  3642.  
  3643.     Volume envelopes are the simplest to describe. With a volume envel-
  3644. ope, it is possible to generate full ADSR synthesised sound. ADSR stands for
  3645. Attack, Decay, Sustain, Release, and describes four steps in the generation
  3646. of a sound. Attack describes how a sound builds up in volume from zero to a
  3647. maximum. Sustain describes the section where the volume is maintained at a
  3648. constant volume for a specific time period. Decay and Release both describe
  3649. how sound volume decreases, the Decay phase(s) following Attack/Sustain pha-
  3650. ses, and the Release phase occurring at the end of the note.
  3651.  
  3652.     When using a volume envelope, the data for the volume envelope is
  3653. entered as for normal sample data. A second area of memory is used for the
  3654. sample data itself. For example, let channel 0 modulate channel 1. For this
  3655. process, AUD0VOL is turned off (channel 0 is not used for actual sound gene-
  3656. ration), AUD0LCH/L is pointed to the envelope data, and AUD0PER can be set
  3657. either to the same rate as AUD1PER for the actual sound data, or to a diff-
  3658. erent value, according to the effect desired. AUD1LCH/L is pointed to the
  3659. sample data, AUD1VOL is set to the maximum value (64), and AUD1PER to the
  3660. sampling rate pertinent for the sample data. Lastly, set USE0V1 in ADKCON and
  3661. set Paula running.
  3662.  
  3663.     A frequency envelope is defined in a different way. Instead of defi-
  3664. ning it as a list of sample data bytes, it is defined as a list of sampling
  3665. rate words as written to the AUDxPER registers. If the base note of the sound
  3666. has a principal frequency of 440 Hz as in the example above, and thus has a
  3667. sampling period value of 508, the values in the frequency envelope can vary
  3668. around this value to create vibrato/tremolo effects, or alternatively, vary
  3669. in one direction to produce ascending/descending pitch. The larger the value
  3670. used, the lower the sampling rate used and the lower the frequency resulting
  3671. when the sample is played. Depending upon the rate of sampling used for the
  3672. frequency envelope, either vibrato or tremolo can be produced.
  3673.  
  3674.     Note that it may be possible to set both USE0V1 and USE0P1 bits. If
  3675. this is done, the data for channel 0 will change BOTH the volume and the fre-
  3676. quency of the output from channel 1, but since there is a fundamental differ-
  3677. ence between amplitude and volume envelope data, the effects cannot readily
  3678. be predicted beforehand.
  3679.  
  3680.     Sound generation problems:in the discourse above, it was mentioned
  3681. that the maximum sampling rate possible was 31399 Hz (ignore the value used
  3682. in the Amiga System Programmer's Guide-it is WRONG). For a digitised sine
  3683. wave of 16 sample data points, the maximum frequency possible for this sine
  3684. wave is 1962.4 Hz. To generate higher frequencies, the number of samples must
  3685. be reduced, so that, for example, a sine curve with 8 samples will have a
  3686. maximum possible reproduction frequency of 3924.8 Hz. But as the number of
  3687. samples decreases, the quality of the sine wave also decreases, until in the
  3688. limiting case, the result is an annoying buzzing noise.
  3689.  
  3690.     One way of circumventing the problem is to digitise multiple waves
  3691. in the waveform instead of just one. This allows higher-frequency waveforms
  3692. to be generated without the problems of waveform degeneration. But a second
  3693. problem occurs with the higher frequencies. There exists a phenomenon assoc-
  3694. iated with high-frequency sound generation called aliasing distortion. This
  3695. comes in two forms, one as the sum of the sampling rate and the desired fre-
  3696. quency, and the second as the difference. So, for example, if the sound is of
  3697. 3KHz frequency, and the sampling rate is 12KHz, the aliasing distortion will
  3698. occur at 9KHz and 15KHz.
  3699.  
  3700.     To eliminate this aliasing distortion, Paula contains a device known
  3701. as a low-pass filter. This has been placed between the output of the D/A con-
  3702. verters and the audio connectors in Paula, and its effect is to allow all of
  3703. the frequencies below 4KHz to pass undisturbed. Frequencies between 4KHz and
  3704. 7KHz are diminished in amplitude, and frequencies above 7KHz are not passed
  3705. at all.
  3706.  
  3707.     In the example cited above, the 3KHz main signal is allowed to pass
  3708. to the speaker undisturbed, but both of the aliasing distortion frequencies
  3709. lie above the 7KHz cutoff point and are eliminated. Should the sampling rate
  3710. be reduced to 9KHz, however, the aliasing distortions now occur at 12KHz and
  3711. 6KHz, and the 6KHz aliasing distortion, although diminished, is still allowed
  3712. past to the speaker.
  3713.  
  3714.     So, when determining sampling rates, to ensure destruction of the
  3715. aliasing distortion and passage of the desired sound signal, the sampling
  3716. rate must be chosen so that it is greater than the frequency of the highest
  3717. frequency component of the sound PLUS the 7KHz cutoff point. So for a sound
  3718. with a maximum frequency component of 4KHz, the sampling rate must be greater
  3719. than 4KHz+7KHz, or 11KHz. Needless to say, given the upper limit of 31KHz on
  3720. the sampling rate as determined earlier, the highest possible frequency com-
  3721. ponent of ANY sound can be no higher than 24KHz. Many people lack the ability
  3722. to hear sounds above 16KHz, but some exceptional persons can hear up to 24KHz
  3723. before the sound exceeds their audible range, including one or two classical
  3724. musicians of note. Most music does not contain notes above 3KHz, so very high
  3725. sound frequencies are generally for specialist applications.
  3726.  
  3727.     Fundamental notes are not the only consideration, however. To main-
  3728. tain the quality of the music, the timbre must be maintained. This is direct-
  3729. ly related to the shape of the curve of the waveform, which in turn depends
  3730. upon maintaining the existence of higher frequency harmonics. Harmonics are
  3731. often separated by octaves, and an increase of one octave results in the fre-
  3732. quency being doubled (octaves and frequencies are related logarithmically).
  3733. So a 3KHz note with several harmonics may have most or all of its harmonics
  3734. destroyed by the low-pass filter. In the extreme case, a square wave which
  3735. consists theoretically of an infinite number of harmonics may be reduced to
  3736. a sine wave by the low-pass filter.
  3737.  
  3738.     Of course, digitising whole sections of music as opposed to single
  3739. notes solves this problem, but at the expense of memory. If the sampling rate
  3740. used by a hardware sampler is 20KHz, and one second of music is sampled, the
  3741. data takes up 20K of memory. This limits the maximum amount of sound that can
  3742. be digitised in one go at that sampling rate to 25.6 seconds (assuming that
  3743. you can fill all of CHIP RAM with the data!). For lower sampling rates more
  3744. data can be digitised, but the memory problem still remains. One solution is
  3745. to digitise sections at a time, compress the resulting data using a suitable
  3746. data compression a;lgorithm, then decompress them into CHIP RAM and play them
  3747. in sequence. Needless to say, the decompression algorithm needs to be fast,
  3748. and synchronised to the sound playing. The data must not be decompressed into
  3749. an area of memory already being used for sound reproduction, hence the decom-
  3750. pression of data MUST NOT catch up with the sound generation! Grabbing the
  3751. data from disc is another possible way around the problem-directly accessing
  3752. the disc tracks yields a data transfer rate of 62500 bytes per second peak,
  3753. and can hence be used to lob in data piecemeal, provided that there is suffi-
  3754. cient disc space. Again, compression/decompression may be needed.
  3755.  
  3756.  
  3757. Hardware:Disc Management
  3758.  
  3759.  
  3760. Disc drives on the Amiga are controlled from two sources, the CIAs and Paula.
  3761. The CIAs govern such features as motor control, drive selection (#6) and head
  3762. movement. The FLAG pin of CIA-B is connected to generate the /INDEX signal of
  3763. the disc drive.
  3764.  
  3765.     The ADKCON register mentioned above in the sound management section
  3766. is also used to control the disc controller. The bits 14-8 of this register
  3767. are used for disc control, and the bit assignments are:
  3768.  
  3769.  
  3770.     Bit    Name    Function
  3771.     ---    ----    --------
  3772.     15    SETIT    see DMACON
  3773.     14,13    PRECOMP    Sets precompensation
  3774.     12    MFMPREC    0=GCR encoding, 1=MFM encoding
  3775.     11    UARTBRK    used for the UART, not used here
  3776.     10    WORDSYNC    1=enable synchronisation
  3777.      9    MSBSYNC    1=enable GCR synchronisation
  3778.      8    FAST    0=4 microseconds/bit(GCR)
  3779.             1=2 microseconds/bit(MFM)
  3780.  
  3781.  
  3782. By appropriate programming of this register, it is possible to enable Amiga
  3783. disc drives to read either MFM or GCR encoded discs. For explanation of the
  3784. terms MFM and GCR, see a comprehensive data source on disc drive operation,
  3785. as I have temporarily forgotten the relevant information.
  3786.  
  3787.     Both encoding mechanisms require appropriate software to generate
  3788. the encoded data before writing to disc, and to decode the data read from the
  3789. disc. The appropriate routines for data encoding/decoding for MFM form part
  3790. of the trackdisk.device - the Amiga uses MFM encoding for its discs as the
  3791. default choice.
  3792.  
  3793.     The need for such encoding is explained simply - raw data cannot be
  3794. written as is to disc. Because of limitations imposed by, among other things,
  3795. the laws of electromagnetism, the data has to be encoded in a manner allowing
  3796. the data to be securely stored in the form of magnetic flux changes on the
  3797. disc surface. I suggest searching out a concise reference work on the subject
  3798. before attempting one's own MFM/GCR encoding/decoding software!
  3799.  
  3800.     As to the existence of these two systems, they have their own hist-
  3801. ory. However, GCR coding is used for Apple Macintosh discs, and there exists
  3802. a Macintosh emulator for the Amiga called A-MAX II using Paula's GCR encoding
  3803. ability to read Mac discs directly.
  3804.  
  3805.     Precompensation is a little bit more difficult to explain. When the
  3806. disc system writes data to the disc, the data is written as a series of flux
  3807. changes onto the magnetic medium. The time for each flux change to occur is
  3808. called the half-zero-bit length, and the gap synthetically introduced to in-
  3809. crease data security for high-speed transfers is the precompensation. Normal-
  3810. ly the faster the data transfer, the higher the precompensation needed to av-
  3811. oid data read/write errors. Four possible settings are provided for by Paula.
  3812.  
  3813.     Now we have the ability to set up the disc controller to provide the
  3814. encoding system, precompensation and disc controller clock rate. Now we need
  3815. to tell Paula where the disc transfer buffer lies. This involves the regis-
  3816. ters DKSPTH (offset $020) and DKSPTL (offset $022). These two registers pro-
  3817. vide a pointer into a buffer in CHIP RAM. This buffer can be used for either
  3818. read or write operations.
  3819.  
  3820.     Having informed Paula of the disc transfer buffer location, we need
  3821. to inform Paula of 1) the length of data to transfer, and 2) the data direc-
  3822. tion (read/write). The register DSKLEN (offset $024) performs these functions
  3823. in one go. The bit assignments of DSKLEN are:
  3824.  
  3825.  
  3826.     Bit    Name    Function
  3827.     ---    ----    --------
  3828.  
  3829.     15    DMAEN    Enable Disc DMA
  3830.     14    WRITE    0=read data from disc, 1=write data to disc
  3831.     13-0    LENGTH    14-bit number : no of WORDS to transfer
  3832.  
  3833.  
  3834. When DMAEN is set to 1, the data transfer is theoretically enabled. The use
  3835. of the word 'theoretically' is deliberate, because Paula contains a mechanism
  3836. to prevent accidental disc writes. Firstly, the DSKEN bit in DMACON must be
  3837. set, and even if it is set, the DMAEN bit of DSKLEN (CARE! confusion may ar-
  3838. ise in the names here!) must be set TWICE before the operation is executed.
  3839. In addition, the WRITE bit must only be set for a genuine write operation! If
  3840. you try changing the value of this bit during the second setting of WRITE, a
  3841. weird and wonderful sequence of events may just occur, leading among other
  3842. things to Paula shuffling off her mortal coil...
  3843.  
  3844.     The orderly sequence for DSKLEN is as follows:
  3845.  
  3846.  
  3847.         MOVE.W    #0,DKSLEN(A5)        ;turn off disc
  3848.         MOVE.W    #$8210,DMACON(A5)        ;enable disc DMA
  3849.                         ;just in case
  3850.  
  3851.         LEA    disbuf(PC),A0
  3852.         MOVE.L    A0,DSKPTH(A5)        ;set up disc buffer
  3853.  
  3854.         CLR.W    D0
  3855.         BSET    #15,D0            ;set DMAEN
  3856.         BSET    #14,D0            ;set WRITE if wanted
  3857.  
  3858.         MOVE.W    #LENGTH,D1        ;amount of data
  3859.                         ;to transfer
  3860.         ADD.W    D0,D1
  3861.  
  3862.         MOVE.W    D1,DSKLEN(A5)        ;set up disc
  3863.  
  3864.         MOVE.W    D1,DSKLEN(A5)        ;now execute!
  3865.  
  3866.         ...            ;here wait until the
  3867.                     ;disc DMA is finished...
  3868.  
  3869.         MOVE.W    #0,DSKLEN(A5)    ;and shut off when done.
  3870.  
  3871.  
  3872. The DSKBLK interrupt is provided in the INTREQ/INTENA registers so that the
  3873. processor can discover when the disc controller has finished. When the number
  3874. of words specified in DSKLEN has been transferred in whichever direction has
  3875. been chosen, the DSKBLK interrupt is signalled. It is generated when the last
  3876. word of data is transferred.
  3877.  
  3878.     To examine the current status of the disc controller, there exists
  3879. the DSKBYTR (offset $01A) register, which is assigned as follows:
  3880.  
  3881.  
  3882.     Bit    Name        Function
  3883.     ---    ----        --------
  3884.     15    BYTEREADY    Signals that byte in lower 8 bits is
  3885.                 valid
  3886.     14    DMAON        Indicates if disc DMA is active. DMAON
  3887.                 set to 1 when DMAEN of DSKLEN is 1 AND
  3888.                 DSKEN of DMACON is 1 (CARE WITH NAMES!)
  3889.     13    DSKWRITE        Copy of WRITE in DSKLEN
  3890.     12    WORDEQUAL    Disc data equals DSKSYNC
  3891.     11-8    Unused
  3892.     7-0    DATA        Current data byte from disc
  3893.  
  3894.  
  3895. Incidentally, it is possible to use this data register to read the data from
  3896. the disc using the 68000 intsead of using DMA (should you want to!). Whenever
  3897. a complete byte is received from the disc, the disc controller sets the BYTE-
  3898. READY bit. The processor then knows that the data in the lower 8 bits is a
  3899. valid data byte. After DSKBYTR is read, the BYTEREADY flag is automatically
  3900. reset. The DMA <system normally performs this without intervention from the
  3901. 68000.
  3902.  
  3903.     Sometimes, instead of reading an entire track of data at once, the
  3904. programmer may wish to read data starting at a specific position. The prog-
  3905. rammer uses the DSKSYNC register (offset $07E) to determine where the disc
  3906. data transfer will begin. The value is an offset, indicating which data word
  3907. the transfer is to begin at (for normal whole-track transfers, the value of
  3908. DSKSYNC is zero). The disc controller maintains a count of words transferred,
  3909. and when that count is less than the value in DSKSYNC, the data is read by
  3910. the DMA system but NOT transferred. When the internal count of words read is
  3911. greater than or equal to the value of DSKSYNC, the data being read is duly
  3912. transferred. Thus the disc controller can be programmed to wait for the syn-
  3913. chronisation mark at the start of a data block.
  3914.  
  3915.     Two other registers exist. These are DSKDAT (offset $026) which is
  3916. used to contain the data written to the disc by the DMA controller, and the
  3917. DSKDATR register (offset $008) which contains data read from the disc. DSK-
  3918. DATR is an early-read register, NOT accessible by the 68000.
  3919.  
  3920.  
  3921. Hardware:Interfaces
  3922.  
  3923.  
  3924. There are three interfaces to handle here. These are the parallel interface,
  3925. the serial interface, and the analogue inputs to the gameports (which can be
  3926. used for other uses apart from game paddles).
  3927.  
  3928.     The parallel interface:this is primarily controlled via the CIAs, &
  3929. the data lines are coupled to PB7-PB0 of CIA-A (i.e., CIAAPRB, whose address
  3930. is $BFE101). The PC output of CIA-A is connected to the DATA READY signal of
  3931. the handshake line, and the FLAG pin to the DATA ACKNOWLEDGE signal. Since
  3932. data register B of each CIA is equipped with handshaking built in, whereby an
  3933. access (read or write) causes PC to go low for one clock cycle, writing to
  3934. CIAAPRB automatically sends out a DATA READY signal. When the connected dev-
  3935. ice responds, it pulls the line connected to FLAG low to signal DATA ACKNOW-
  3936. LEDGE, and the FLAG bit in the ICR is set. Because of this, it is possible to
  3937. process data output to the Centronics interface via an interrupt routine, &
  3938. allow programs to continue with other processing while the interrupt routine
  3939. handles the output - ideal for printer spooling, for example.
  3940.  
  3941.     The handshaking process can also be used for data INPUT from the
  3942. Centronics interface (assuming a bidirectional perpipheral is connected!).
  3943. PC and FLAG are handled automatically by the CIA, and handling the FLAG int-
  3944. errupt is virtually all that the programmer needs to do under normal circum-
  3945. stances.
  3946.  
  3947.     CIA-B is used for the SELECT and BUSY signals, bit 2 of CIABPRA (at
  3948. address $BFD000) being SELECT, and bit 0 being BUSY. The BUSY signal is used
  3949. for communication with slow peripherals (e.g., printers), and the interrupt
  3950. routine can also wait for the BUSY signal to change before continuing output
  3951. to a printer.
  3952.  
  3953.     The serial interface:the serial interface is controlled by a combin-
  3954. ation of CIA registers and Paula registers. The CIA connections for the ser-
  3955. ial interface are:
  3956.  
  3957.  
  3958.     /DTR signal    :    CIA-B PA7
  3959.     /RTS signal    :    CIA-B PA6
  3960.     /CD  signal    :    CIA-B PA5
  3961.     /CTS signal    :    CIA-B PA4
  3962.     /DSR signal    :    CIA-B PA3
  3963.  
  3964.  
  3965. All of these signals are sent through inverter logic as part of the RS-232
  3966. driver hardware, and so the signals are active low. Setting the corresponding
  3967. CIA-B bit to 0 sets the corresponding RS-232 line to high. TAKE CAREFUL NOTE
  3968. OF THIS! Forgetting the inverse logic of this RS-232 interface is a common
  3969. source of interfacing problems.
  3970.  
  3971.     When using RTS/CTS protocol, RTS should be made an output (set the
  3972. corresponding bit in CIABDDRA) and CTS an input (clear the appropriate DDRA
  3973. bit). I am not currently sure how to handle XON/XOFF, so until I have access
  3974. to the appropriate data, I shall leave XON/XOFF undocumented.
  3975.  
  3976.     One feature of serial data transfer using RS-232 is that clock sig-
  3977. nals are not provided. This means that both sender and receiver must provide
  3978. their own timing, and that the times must match for secure data transfer. A
  3979. set of standard baud rates exist for RS-232, typical values being 300 baud,
  3980. 1200, 2400, 4800 and 9600 baud. Some fast peripherals (e.g., the new modems
  3981. for mainframe communications using SYSTEM-X exchanges) can have a maximum
  3982. baud rate of 38400 baud (but since they're £5,000 each, few readers of this
  3983. DOC file will have one coupled to their Amigas...) and high baud rates are
  3984. also a feature of experimental computer-moderated radio transmissions using
  3985. short-wave radio.
  3986.  
  3987.     The serial interface controller, or UART (this admonitive acronym
  3988. stands for 'Universal Asynchronous Receiver/Transmitter', which is a lot of
  3989. fun to try and say after several Bacardis) allows setting of the baud rate
  3990. in the SERPER register (custom chips, offset $032, write-only). This regis-
  3991. ter also controls the data length to some extent. Bit 15 (the LONG bit), if
  3992. set, makes the length of the receive data 9 bits instead of 8. The remain-
  3993. ing 15 bits determine the baud rate.
  3994.  
  3995.     Baud rate determination is indirect. Again, the number used is the
  3996. number of bus cycles (just as for audio data sampling rates) taken to trans-
  3997. mit one byte of data. If it takes N bus cycles to transmit a byte, the number
  3998. N-1 must be written to SERPER (for some perverse reason). So the relationship
  3999. between baud rate and the value to write into SERPER (here designated as S)
  4000. is
  4001.  
  4002.  
  4003.         S    =    (1 / (B * 2.79365 * 10E-7) ) - 1
  4004.  
  4005.  
  4006. where B is the baud rate, and 2.79365 * 10E-7 is the time taken for one bus
  4007. cycle (279.365 nanoseconds). So, for 4800 baud transmit/receive rate, the
  4008. value is
  4009.  
  4010.  
  4011.         S = (1/4800 * 2.79365*10E-7) - 1
  4012.  
  4013.  
  4014. which is 744.738. Rounding to the nearest integer, we have 745. So to select
  4015. 4800 baud we use
  4016.  
  4017.  
  4018.         move.w    #745,SERPER(a5)
  4019.  
  4020.  
  4021. for 8-bit data transfers, and
  4022.  
  4023.  
  4024.         move.w    #$8000+745,SERPER(a5)
  4025.  
  4026.  
  4027. for 9-bit receives.
  4028.  
  4029.     Ok, we can now set the baud rate, and have access to the control
  4030. signals. The other registers we need are the Paula serial data registers
  4031. (Cross-reference #2):
  4032.  
  4033.  
  4034.     Register        Offset    Function
  4035.     --------        ------    --------
  4036.     SERDAT          030    Contains data to send (RS-232 output)
  4037.     SERDATR          018    Contains data to read (RS-232 input)
  4038.  
  4039.  
  4040. The SERDATR register for data reading (RS-232 input mode) has several bits
  4041. allocated to various functions. The bit assignments for SERDATR are:
  4042.  
  4043.  
  4044.     Bit    Name    Function
  4045.     ---    ----    --------
  4046.     15    OVRUN    Overrun of receiver shift register if set
  4047.     14    RBF    Receive buffer full if set
  4048.     13    TBE    Transmit buffer empty if set
  4049.     12    TSRE    Transmit shift register empty if set
  4050.     11    RXD    Matches level on RXD line
  4051.     10    Unused
  4052.      9    STP    Stop Bit Value
  4053.      8    DB8    Depends on LONG in SERPER
  4054.     7-0    DB7-0    Receive data buffer bits 7-0
  4055.  
  4056.  
  4057. SERDAT (offset $030) is used to contain the data to be transmitted from the
  4058. Amiga. Because of the time taken for serial data transfer using normal RS-232
  4059. protocols, there is no provision for a data buffer pointer and a DMA control
  4060. read/write system to automatically read in or write out a block of data of a
  4061. given size, as the need was felt not to exist by the designers. The maximum
  4062. possible data transfer rate corresponds to a SERPER value of zero, and equals
  4063. approximately 3,580,000 baud! Not a regularly selected baud rate...few appli-
  4064. cations need this kind of speed (usually confined to military systems, which
  4065. also possess inbuilt data encryption, reversible frequency modulated pertur-
  4066. bation of the data stream and other weird features not present on the Amiga)
  4067. and it is very unlikely that readers of this DOC file will ever need it.
  4068.  
  4069.     Two interrupts are provided for handling serial transfers. The RBF
  4070. (Receive Buffer Full) interrupt handled via the IPL5 interrupt vector is the
  4071. interrupt used for handling RS-232 transfers from the outside world to the
  4072. Amiga, and the TBE (Transmit Buffer Empty) interrupt handled via the IPL1
  4073. interrupt vector is used to handle RS-232 transfers from the Amiga to the
  4074. outside world. Both interrupt vectors should be initialised appropriately and
  4075. the interrupt code should principally restrict itself to either sending or
  4076. receiving a byte of data. Configuring the baud rates and other allied func-
  4077. tions should be left to other routines called by the main program.
  4078.  
  4079.     The procedures are as follows:
  4080.  
  4081.  
  4082. * Reading a byte of data from RS-232
  4083. * This is interrupt code, so put an RTE after it
  4084. * if using 'as is'. If using AmigaDos, there are
  4085. * other ways of doing it - see elsewhere.
  4086.  
  4087. * assumes ptr to custom chips in A5!!
  4088.  
  4089.  
  4090.         move.w    INTREQR(a5),d0    ;get interrupt request
  4091.         bclr    #11,d0        ;RBF interrupt?
  4092.         beq.s    not_RBF        ;no
  4093.  
  4094.         move.w    SERDATR(a5),d0    ;get received data (clear RBF)
  4095.         move.w    d0,ser_word    ;save it
  4096.  
  4097.         move.w    d0,INTREQ(a5)    ;and acknowledge interrupt
  4098.                     ;(see note below)
  4099.  
  4100.  
  4101. not_RBF        ...
  4102.  
  4103.  
  4104. The RBF (Receive Buffer Full) bit is set in SERDATR and INTREQ/R whenever a
  4105. data word is transferred from Paula's internal shift register to the SERDATR
  4106. register. At this point, SERDATR should be read, to clear space for the next
  4107. incoming data word. Reading the next data word clears RBF, and signals that
  4108. SERDATR is ready to receive the next data word being read into Paula's int-
  4109. ernal shift register.
  4110.  
  4111.     If SERDATR is not read, and the shift register has received another
  4112. complete data word, OVRUN is set. This signals that no more data can be rec-
  4113. eived because both SERDATR and the shift register contain inputted data. When
  4114. SERDATR is read under these conditions, OVRUN is reset, and RBF also. RBF is
  4115. then immediately set again and the full contents of the internal shift regis-
  4116. ter are loaded into SERDATR again, allowing more data to enter the shift reg-
  4117. ister. Obviously, once RBF is set again, the data must be read from SERDATR
  4118. again.
  4119.  
  4120.     The format of the data to be read is determined by SERDATR and SER-
  4121. PER. If the LONG bit of SERPER is set, the data is 9 bits, else 8 bits. If
  4122. the data is 8 bits, then bits 9 and 10 mark the stop bits, if present, and
  4123. are set if there is a stop bit there. If the data is 9 bits, bit 10 is the
  4124. stop bit if present, again set if a stop bit encountered. Note that all data
  4125. is sent with one start bit, which always has the value 0. This applies both
  4126. to reception and transmission, and the hardware detects the end of a data
  4127. word by noting the transmission from the 1 of a stop bit to the 0 of the next
  4128. start bit. Note that when the data transmitter has finished sending its data
  4129. to the Amiga, the RBF bit will never be set after the last word has been pro-
  4130. cessed, and the interrupt routine will never be called from this point on.
  4131.  
  4132.     Usually, RS-232 systems signal this, either by sending a data byte
  4133. or bytes at the start indicating the size of the data block being transmit-
  4134. ted, or by sending a special 'end of transmission' character at the end of
  4135. transmission. Two typical choices are CTRL-D (known as the ASCII EOT char-
  4136. acter) or CTRL-Z (EOF, or end of file, on many systems). If the transmission
  4137. consists of binary data instead of ASCII characters, then either the start
  4138. of the transmission must contain the byte count of the block, or else another
  4139. means of signalling end of transmission is required, as any of the control
  4140. characters could be a valid data byte, unless an encoding scheme is used.
  4141.  
  4142.  
  4143. * Writing a byte of data to RS-232
  4144. * Again,interrupt code, pointer to the
  4145. * custom chips in A5.
  4146.  
  4147.  
  4148.         move.w    INTREQR(a5),d0    ;get interrupt request
  4149.         bclr    #0,d0        ;TBE interrupt?
  4150.         beq.s    not_TBE        ;no
  4151.  
  4152.         move.w    ser_word,d0    ;get data to send
  4153.         move.w    d0,SERDAT(a5)    ;send it (clear TBE)
  4154.  
  4155.         move.w    d0,INTREQ(a5)    ;acknowledge interrupt
  4156.  
  4157.  
  4158. not_TBE        ...
  4159.  
  4160.  
  4161. The data to be output in this case is written to SERDAT. It is then immedia-
  4162. tely transferred to the output internal shift register. This is signalled by
  4163. the TBE bit, which is set to indicate that SERDAT is able to receive more
  4164. data. Once TBE is set, more data should be written to SERDAT to maintain the
  4165. data flow. Should this not occur, and the output shift register is emptied
  4166. before SERDAT is reloaded, then the TSRE (Transmit Shift Register Empty) bit
  4167. is set. This is cleared when SERDAT is loaded, as is TBE. But TBE is immedia-
  4168. tely set again as the contents of SERDAT are sent to the output shift regis-
  4169. ter, and TBE is cleared again, allowing more data to be written.
  4170.  
  4171.     The format of the data to be sent is determined by SERDAT. The data
  4172. formats for different cases are:
  4173.  
  4174.  
  4175.     8 bit data, 1 stop bit    : 00000001 dddddddd
  4176.  
  4177.     8 bit data, 2 stop bits    : 00000011 dddddddd
  4178.  
  4179.     9 bit data, 1 stop bit    : 0000001d dddddddd
  4180.  
  4181.  
  4182. To stop transmission of data, one bit of the ADKCON register (offset $09E) is
  4183. provided, the UARTBRK bit (bit 11). Setting this bit using the instruction
  4184.  
  4185.  
  4186.         move.w    #$8800,ADKCON(a5)
  4187.  
  4188.  
  4189. (ADKCON uses the SETIT mechanism-see DMACON) stops serial data transfer and
  4190. clears TXD (the transmit data line) of the serial port.
  4191.  
  4192.     Analogue inputs:the gameports possess two analogue inputs each, and
  4193. it is possible to connect game paddles to them or other analogue signal gene-
  4194. rating equipment. Game paddles usually use a sliding or twist knob to change
  4195. the resistance of a potentiometer (known as a 'pot' for short - hence the use
  4196. of POTxxxx register names for this interface!).
  4197.  
  4198.     Analogue joysticks, with a potentiometer for the X and the Y direc-
  4199. tion, can also be connected. The values that these produce are read in the
  4200. POTxDAT registers (POT0DAT, offset $012, POT1DAT, offset $014). Bits 0-7 are
  4201. used for the X-value, and bits 8-15 for the Y-value.
  4202.  
  4203.     Now, how does this work? Well, Paula contains a circuit to handle a
  4204. simple analogue-to-digital conversion. The requirement is that the maximum
  4205. resistance of the potentiometers should be 470 Kilohms (with a tolerance of
  4206. plus or minus ten percent). One side of the potentiometer is connected to the
  4207. 5-volt power supply, and the other to one of the analogue inputs. These lead
  4208. internally to Paula and to a capacitor, one for each input, connected between
  4209. the input and ground.
  4210.  
  4211.     The paddle outputs are placed briefly at ground, discharging the ca-
  4212. pacitors. Also, the counters in POTxDAT are cleared. For each raster line,
  4213. the counters are incremented by one while the capacitors are charged through
  4214. the resistors. When the voltage across the capacitor exceeds a preset value,
  4215. the corresponding counter is stopped. Thus the counter state is directly pro-
  4216. portional to the input resistance. Small values equal low resistances, large
  4217. values equal high resistances.
  4218.  
  4219.     The POTGO register (Cross-reference #7) determines whether the ana-
  4220. logue pins are inputs or outputs. The bits are assigned as follows:
  4221.  
  4222.  
  4223.     Bit    Name    Function
  4224.     ---    ----    --------
  4225.     15    OUTRY    1=gameport 1 POTY bit is output, 0=input
  4226.     14    DATRY    Gameport 1 POTY data bit
  4227.     13    OUTRX    1=gameport 1 POTX bit is output, 0=input
  4228.     12    DATRX    Gameport 1 POTX data bit
  4229.     11    OUTLY    1=gameport 0 POTY bit is output, 0=input
  4230.     10    DATLY    Gameport 0 POTY data bit
  4231.      9    OUTLX    1=gameport 0 POTX bit is output, 0=input
  4232.      8    DATLX    Gameport 0 POTX data bit
  4233.     7-1    unused
  4234.      0    START    Discharge capacitors & begin analogue
  4235.             measurement
  4236.  
  4237.  
  4238. A write access to POTGO (offset $034) clears both POTxDAT registers. POTGOR
  4239. also exists (offset $016) to allow the states to be read.
  4240.  
  4241.     Normally, START is set to 1 at the start of the vertical blank int-
  4242. erval, and the valid potentiometer values can be read at the start of the
  4243. next VBL, immediately prior to setting START to 1 again.
  4244.  
  4245.     If the corresponding OUTxx bit above is set to 1, the corresponding
  4246. line is treated as a digital output, and the corresponding DATxx bit is sent
  4247. out along it. If OUTxx=0, then DATxx in POTGOR yields the current state of
  4248. those lines as digial outputs.
  4249.  
  4250.     Paddle buttons use the same bits as the joystick data registers (ho,
  4251. hum!). The assignments are:
  4252.  
  4253.  
  4254.         Gameport 0        Gameport 1
  4255.         ----------        ----------
  4256.  
  4257. Left Button    JOY0DAT bit 9        JOY1DAT bit 9
  4258.  
  4259. Right Button    JOY0DAT bit 1        JOY1DAT bit 1
  4260.  
  4261.  
  4262. For each of these, the bit is 1 if the button is pressed.
  4263.  
  4264.  
  4265. Hardware:Mouse, Keyboard, Joysticks
  4266.  
  4267.  
  4268. I assume that most of those readers requiring this file for hardware documen-
  4269. tation know what a keyboard, a mouse and a joystick are. Some may even have
  4270. dismantled several of these items (I have-much to the dismay of those people
  4271. whose equipment I have dissected!) and found out about the inner workings of
  4272. the basic hardware. However, there exist extra components within these pieces
  4273. of hardware whose function needs a little extra explanation.
  4274.  
  4275.     Modern keyboards are no longer simply a matrix of switches. Most of
  4276. the keyboards on modern computers have internal controller chips of their own
  4277. with their own RAM and ROM, allowing customisation and configuration of the
  4278. keyboard. IBM PCs (ugh!) use an Intel 8047 controller, Sinclair QLs (yeuck!)
  4279. use an Intel 8049, Atari STs (duh...) use a 6301 processor chip (this was at
  4280. one time the heart of expensive desktop computers!) and the Amiga? Well, the
  4281. Amiga uses the MOS 6500/1 processor. So what? Well, a 6500/1 is really a 6502
  4282. processor, as found in the PET/VIC-20/Commodore 64, with on-chip RAM and ROM.
  4283. The ROM is mask-programmed with the control program for the Amiga keyboard.
  4284. Cross-reference #1:the CIAs are coupled via several links to the 6500/1 for
  4285. keyboard communication.
  4286.  
  4287.     So, if it wasn't for the mask programmed ROM, in theory anyone with
  4288. a 6502 assembler and the motivation could write his own keyboard controller
  4289. program for the Amiga. Sad to say, the existence of a control program embed-
  4290. ded in ROM, plus the one-way data traffic (keyboard to Amiga) makes this im-
  4291. possible. Atari ST keyboard controllers CAN be reprogrammed, but I warn any-
  4292. one tempted to try, it is HARD.
  4293.  
  4294.     The 6500/1 has a 2K ROM, 64 bytes of static RAM, 4 bidirectional 8-
  4295. bit ports, a 16-bit counter with its own control input, and a clock generator
  4296. of its own. This chip is interfaced to the Amiga via two precision 556 timer
  4297. chips. These provide a reset signal for the Amiga. The mechanism by which the
  4298. reset mechanism is provided is interesting - more later.
  4299.  
  4300.     The 6500/1 reads the keyboard matrix via ports C and D (the 6500/1
  4301. has four I/O ports on-chip) to obtain details about which key has been either
  4302. pressed or released. This information is converted from the bitwise port in-
  4303. formation, into a raw key code passed out to the Amiga via port A. This data
  4304. is transmitted serially, and the requisite line from the 6500/1 is connected
  4305. to the SP input line of CIA-A. The CNT line of the same CIA provides the key-
  4306. board system with the clock signal for signal synchronisation.
  4307.  
  4308.     Having scanned the matrix, the 6500/1 returns raw key codes whenever
  4309. there is a state change in the keyboard. If a key is pressed, the code for
  4310. that key is sent. If that key is released, the code for that key, with bit 7
  4311. set, is sent to signal 'key released'. If a different key is pressed before
  4312. the release of the original key, the new keypress is sent first. The keyboard
  4313. events are sent in the order of occurrence where possible.
  4314.  
  4315.     Special keys are wired into a different part of the matrix, so that
  4316. keycode clashes do not occur with the special keys SHIFT, CONTROL, ALT & the
  4317. two AMIGA keys. Both left and right SHIFT, left and right ALT, and left and
  4318. right AMIGA are given their own separate keycodes, making for a massive num-
  4319. ber of keycoding possibilities. CAPS LOCK also has its own key code, and is
  4320. treated somewhat differently. The 6500/1 simulates a push-button with this
  4321. key, no release information being supplied. The CAPS LOCK key state is only
  4322. judged to have changed when pressed - releasing the CAPS LOCK key is ignored
  4323. by the 6500/1. When pressed the first time, the LED lights up, and a code is
  4324. sent corresponding to 'key pressed'. The second time CAPS LOCK is pressed, at
  4325. which point the LED becomes unlit, the code for 'key released' (bit 7 set) is
  4326. sent. This is the only key treated thus - all other keys have their pressed/
  4327. released events handled in the normal way described above.
  4328.  
  4329.     Key code groups are :
  4330.  
  4331.     $00 - $3F    : Normal ASCII letter keys in the main
  4332.               keyboard section between the grey ENTER
  4333.               and the CAPS LOCK key, plus the numeric
  4334.               keypad keys except ENTER.
  4335.  
  4336.     $40 - $4F    : Codes of standard special keys, such as
  4337.               the SPACE BAR, RETURN, TAB, BACKSPACE,
  4338.               DEL, ESC, numeric keypad ENTER.
  4339.  
  4340.     $50 - $5F    : Function keys F1-F10, HELP.
  4341.  
  4342.     $60 - $6F    : SHIFT, ALT, CONTROL, AMIGA and CAPS LOCK
  4343.               keys.
  4344.  
  4345.  
  4346. I shall supply the codes for the special keys individually. To work out the
  4347. other keys, it is possible to write a piece of code to scan the keyboard and
  4348. read the raw key codes. More of this later. The special key codes are :
  4349.  
  4350.  
  4351.     Key        Code
  4352.     ---        ----
  4353.     LEFT SHIFT    $60
  4354.     RIGHT SHIFT    $61
  4355.     CAPS LOCK    $62
  4356.     CONTROL        $63
  4357.     LEFT ALT        $64
  4358.     RIGHT ALT    $65
  4359.     LEFT AMIGA    $66
  4360.     RIGHT AMIGA    $67
  4361.  
  4362.  
  4363. There are also special codes sent for certain special functions. These are:
  4364.  
  4365.  
  4366.     Keycode        Function
  4367.     -------        --------
  4368.     $F9        Last key code sent was incorrect
  4369.     $FA        Keyboard buffer of 6500/1 is full
  4370.     $FC        Error in keyboard self test (AGH! REPAIR TIME!)
  4371.     $FD        Start of keys held down on power up
  4372.     $FE        End of keys held down on power up
  4373.  
  4374.  
  4375. The $F9 code is sent if there has been disruption of the keyboard linkage. On
  4376. the A500, this usually means time to get the Amiga mended, but on A100/A2000
  4377. machines this can result from unplugging a keyboard & then plugging in a new
  4378. keyboard while the Amiga is switched on. This allows the keyboard resynchron-
  4379. isation system to be activated, re-establishing secure communications.
  4380.  
  4381.     The 6500/1 has an internal character buffer of 10 characters. If the
  4382. buffer becomes full (because software is not reading it quickly enough), the
  4383. 6500/1 sends the $FA code to indicate a full keyboard buffer, and that sub-
  4384. sequent keypresses will be lost.
  4385.  
  4386.     Keyboard data communications are always conducted from the keyboard
  4387. to the Amiga. The Amiga sends handshaking signals to the keyboard and also a
  4388. clock signal for data transfer synchronisation.
  4389.  
  4390.     The actual order in which the bits are sent is not the usual order
  4391. of 76543210, but 65432107. So when the data byte is received, it needs to be
  4392. rotated one bit position to obtain the true keycode. The CIA shift register
  4393. of CIA-A contains the data once read, and sends a level-2 interrupt once the
  4394. data has been received. The level-2 interrupt code should then read that data
  4395. byte, output the handshake pulse and save the received code somewhere safe to
  4396. be processed later by a user program. 
  4397.  
  4398.     Keycodes furthermore are inverted, because the circuitry is designed
  4399. as ACTIVE LOW. This means that a low voltage corresponds to a 1, and a high
  4400. voltage corresponds to a 0. To obtain the keycode, the bits must be inverted
  4401. back to the normal form. 
  4402.  
  4403.     Basically, the 6500/1 puts the data bits on its data line (KDAT),
  4404. plus a 20-microsecond low pulse on the clock line (KCLK). Between each of the
  4405. data pulses, 40-microsecond pauses are placed. Hence data transfer rate is 1
  4406. bit every 60 microseconds, or 16667 bits per second (16666 baud). After the
  4407. last data bit has been sent, the 6500/1 waits for a handshake pulse. This is
  4408. performed by the Amiga pulling KCLK low for 75 microseconds the moment that
  4409. the last data bit is received.
  4410.  
  4411.     To handle the keyboard interface, the kind of code I would use looks
  4412. like this, on occasions when the operating system is being bypassed:
  4413.  
  4414.  
  4415. * complete level 2 interrupt handler for CIA-A
  4416. * to initialise CIA-A to activate this routine properly
  4417. * initialise with CIAAICR = $10, CIAACRA = $40 in the
  4418. * main program. This sets SPMOD = input,
  4419. * INMODE = CNT, generate interrupt when SP full.
  4420. * Don't forget to point IPL2 vector to this code as well!
  4421.  
  4422.  
  4423. ciaint        move.w    #$2700,sr    ;lock out higher ints
  4424.                     ;just in case
  4425.  
  4426.         move.l    d0,-(sp)        ;keep this
  4427.  
  4428.         move.w    INTREQR(a5),d0
  4429.         btst    #3,d0        ;CIA interrupt?
  4430.         beq.s    ciaint_1        ;nope!
  4431.  
  4432.         move.w    #$0008,INTREQ(a5)    ;system acknowledge IRQ
  4433.  
  4434.         move.b    CIAAICR,d0    ;check CIA-A interrupt reg
  4435.         btst    #7,d0        ;CIA interrupt proper?
  4436.         beq.s    ciaint_1        ;no, cock up somewhere so ignore
  4437.  
  4438.         btst    #3,d0        ;SP data full?
  4439.         beq.s    ciaint_1        ;no, cock up somewhere so ignore
  4440.  
  4441.         addq.w    #1,ciacount    ;cia interrupt counter
  4442.  
  4443.         move.b    CIAASP,d0    ;get key code from keyboard
  4444.         or.b    #$40,CIAACRA    ;set SPMODE=output (pulls
  4445.                     ;KCLK low!)
  4446.         not.b    d0
  4447.         ror.b    #1,d0
  4448.         move.b    d0,rawkey    ;proper raw key code
  4449.  
  4450.         moveq    #8,d0        ;wait for 75 microsecs
  4451. ciaint_0        subq.w    #1,d0        ;while pulling KCLK low
  4452.         bne.s    ciaint_0
  4453.  
  4454.         and.b    #$BF,CIAACRA    ;SPMODE=input again
  4455.  
  4456. ciaint_1        move.l    (sp)+,d0
  4457.         rte
  4458.         
  4459.  
  4460. ciacount        dc.w    0
  4461. rawkey        dc.b    0,0
  4462.  
  4463.  
  4464. Keyboard reset mechanism:this is managed by the 6500/1. Pressing the sequence
  4465. of keys CTRL-AMIGA-AMIGA causes a hard reset. The 6500/1 control program will
  4466. sense this sequence, and pull KCLK low for about 0.5 seconds. This tells the
  4467. reset circuit of the Amiga to generate a hard reset. After one or more of the
  4468. keys are released, the 6500/1 also undergoes a reset, rebooting its control
  4469. program from scratch, signalled by flashing of the CAPS LOCK LED. Since KCLK
  4470. is connected to the CNT pin of CIA-A, and the above interrupt routine shows a
  4471. way of pulling KCLK low for 75 microseconds, it needs little imagination to
  4472. see that increasing the delay will allow software generation of a hard reset!
  4473. Just set SPMODE = OUTPUT for CIA-A, and hang the processor. After 0.5 seconds
  4474. or more, the Amiga will reset!
  4475.  
  4476.     Mouse handling:the mouse counters are part of Denise. There are two
  4477. registers, called JOY0DAT (offset $00A) and JOY1DAT (offset $00C) for each of
  4478. the gameports 0 and 1. Just to relieve the confusion, the back panel of the
  4479. A500 says 'Joystick port 1' and 'Joystick port 2'. Subtract 1 from the num-
  4480. bers to get the appropriate gameport counter. The high byte of each counter
  4481. counts the vertical pulse count from 0 to 255, the low byte the horizontal
  4482. pulse count from 0 to 255.
  4483.  
  4484.     The mouse counters count 200 pulses per inch (about 79 pulses/cm).
  4485. This makes the counters overflow after the mouse has moved about 4 cm. To
  4486. counter this, word-wide counters should be set up in software, and the actual
  4487. gameport counters used to update these. This is normally done by the opera-
  4488. ting system during the vertical blank interrupt. The following code is an
  4489. extract from a vertical-blank interrupt routine that I have used to handle
  4490. mouse counters:
  4491.  
  4492.  
  4493. ;read mouse during VBL interrupt. mousex/y = old value of
  4494. ;counters, mouseh/v = horiz/vert movement
  4495.  
  4496.  
  4497.         move.w    JOY0DAT(a5),d0    ;get mouse counter
  4498.         move.w    d0,newmouse    ;save for later
  4499.         and.w    #$FF,d0        ;x counter
  4500.         sub.w    mousex,d0    ;difference old-new
  4501.         cmp.w    #-127,d0    ;underflow?
  4502.         bge.s    vblmouse1    ;no
  4503.         neg.w    d0        ;else -255-diff
  4504.         sub.w    #255,d0
  4505.         bra.s    vblmouseh    ;store it
  4506. vblmouse1    cmp.w    #127,d0        ;overflow?
  4507.         ble.s    vblmouseh    ;no
  4508.         neg.w    d0        ;else 255-diff
  4509.         add.w    #255,d0
  4510. vblmouseh    move.w    d0,mouseh    ;store horiz difference >0 = right
  4511.         move.w    newmouse,d0    ;get saved mouse counter
  4512.         lsr.w    #8,d0        ;get vertical count
  4513.         sub.w    mousey,d0    ;difference old-new
  4514.         cmp.w    #-127,d0    ;underflow?
  4515.         bge.s    vblmouse2    ;no
  4516.         neg.w    d0        ;else -255-diff
  4517.         sub.w    #255,d0
  4518.         bra.s    vblmousev    ;store it
  4519. vblmouse2    cmp.w    #127,d0        ;overflow?
  4520.         ble.s    vblmousev    ;no
  4521.         neg.w    d0        ;else 255-diff
  4522.         add.w    #255,d0
  4523. vblmousev    move.w    d0,mousev    ;store vert difference >0 = down
  4524.         moveq    #0,d0
  4525.         move.w    newmouse,d0    ;get mouse counters
  4526.         lsl.l    #8,d0        ;split across 2 words
  4527.         lsr.w    #8,d0        ;isolate x
  4528.         move.w    d0,mousex    ;save
  4529.         swap    d0        ;get y
  4530.         move.w    d0,mousey    ;save
  4531.  
  4532.  
  4533. newmouse    dc.w    0
  4534. mousex        dc.w    0
  4535. mousey        dc.w    0
  4536. mouseh        dc.w    0
  4537. mousev        dc.w    0
  4538.  
  4539.  
  4540. The algorithm used is as follows:the assumption is made that the mouse coun-
  4541. ters are not changed by more than 127 pulses between reads. Both old and new
  4542. values are maintained, and new compared with old. The value
  4543.  
  4544.  
  4545.         diff = old - new
  4546.  
  4547.  
  4548. is calculated. If 0 < diff < 127, the mouse movement was either right or down
  4549. without overflow. If -127 < diff < 0, the mouse movement was either left or
  4550. up, without overflow. If diff > 127, movement was right or down, with a coun-
  4551. ter overflow. If diff < -127, movement was left or up, with a counter under-
  4552. flow. For overflow, the actual mouse movement is computed as 255-diff, while
  4553. for an underflow, the actual mouse movement is computed as -255-diff.
  4554.  
  4555.     To reset the mouse counters, use the JOYTEST register (offset $036).
  4556. This register is unusual. The register bit allocation is as follows:
  4557.  
  4558.  
  4559.         Y Y Y Y Y Y y y X X X X X X x x
  4560.  
  4561.  
  4562. The Y bits are the upper 6 bits of the vertical counter, and the X bits are
  4563. the upper 6 bits of the horizontal counter. The yy and xx bits are connected
  4564. directly to the mouse input signals, and are not located anywhere in memory.
  4565. So these values cannot be changed at all in software. JOYTEST has the effect
  4566. of resetting both sets of mouse counters, making JOY0DAT and JOY1DAT equal in
  4567. value. Whatever value is sent to JOYTEST is sent to both of the JOYxDAT regi-
  4568. sters.
  4569.  
  4570.     The mouse buttons are handled separately. If the mouse is attached
  4571. to port 0, the signals occur as follows:
  4572.  
  4573.  
  4574.     LEFT BUTTON        : CIAAPRA, Bit 6
  4575.     RIGHT BUTTON        : DATLY of POTGO (#7)
  4576.     MIDDLE BUTTON(*)    : DATLX of POTGO (#7)
  4577.  
  4578.  
  4579. For game port 1, the signals are:
  4580.  
  4581.  
  4582.     LEFT BUTTON        : CIAAPRA, Bit 7
  4583.     RIGHT BUTTON        : DATRY of POTGO (#7)
  4584.     MIDDLE BUTTON (*)    : DATRX of POTGO (#7)
  4585.  
  4586.  
  4587. For all of these, a zero bit value means that the button is PRESSED.
  4588.  
  4589. Joysticks are handled in a similar way-they use the same counters & JOYTEST.
  4590. However, to sense the direction in which the joystick is moved, the software
  4591. algorithm differs. Basically, the following table holds:
  4592.  
  4593.  
  4594.     Joystick Right        : Bit 1 JOYxDAT = 1
  4595.     Joystick Left        : Bit 9 JOYxDAT = 1
  4596.     Joystick Back        : (Bit 1 EOR Bit 0) = 1
  4597.     Joystick Forward    : (Bit 9 EOR Bit 1) = 1
  4598.  
  4599.  
  4600. The following piece of code can be used to generate direction indicators for
  4601. the joystick (here called DX for left/right, DY for up/down):
  4602.  
  4603.  
  4604.         move.w    JOY0DAT(a5),d0    ;get joystick value
  4605.         move.w    d0,d1        ;& copy it
  4606.         lsr.w    #1,d1        ;shift copy left
  4607.  
  4608.         moveq    #0,d2        ;clear DX, DY
  4609.  
  4610.         btst    #1,d0        ;bit 1 set (right) ?
  4611.         beq.s    notright        ;no
  4612.         move.w    #1,d2
  4613.  
  4614. notright    btst    #9,d0        ;bit 9 set (left) ?
  4615.         beq.s    notleft        ;no
  4616.         move.w    #-1,d2
  4617.  
  4618. notleft        swap    d2
  4619.  
  4620.         eor.w    d0,d1
  4621.         btst    #0,d1        ;result 1 (back) ?
  4622.         beq.s    notback
  4623.         move.w    #-1,d2
  4624.  
  4625. notback        btst    #8,d1        ;result 1 (forward) ?
  4626.         beq.s    notfront
  4627.         move.w    #1,d2
  4628.  
  4629. notfront    swap    d2
  4630.  
  4631.  
  4632. Now D2 contains the value DX in the low word, DY in the high word, and the
  4633. programmer can handle this value ad lib. This method allows diagonal joystick
  4634. values to be managed (the example in the Amiga System Programmer's Guide does
  4635. not allow this) in a way that is useful for such things as games.
  4636.  
  4637.         Note that to ensure diagonal values are read properly, it
  4638. might be prudent to embed the code above as a subroutine, save the value in
  4639. D2 in D3 after the first call, and then call the subroutine a few times more,
  4640. each time ORing the result of D2 into D3. This allows transient diagonal joy-
  4641. stick values to be strobed in case the joystick response is poor, a standard
  4642. trick used by games writers on systems with known poor joystick responses.
  4643.  
  4644.     The joystick fire buttons for each port correspond to the left mouse
  4645. buttons in each case-the states of each are read from the same bits of the
  4646. same register (see mouse above).
  4647.  
  4648.  
  4649. Hardware:Some Notes
  4650.  
  4651.  
  4652. This file does NOT contain information about the Enhanced Chip Set (from here
  4653. on known as the ECS). The ECS is able to access a CHIP RAM range of 1MB as
  4654. opposed to the 512K of the standard chip set, and I assume this is achieved
  4655. by expanding the various pointer high word registers to 4 bits wide, making
  4656. a 20-bit address whole. Mind you, I have discovered that making logical ass-
  4657. umptions such as this about Commodore hardware can lead a programmer right
  4658. up shit creek without a paddle.
  4659.  
  4660.     The ECS is also supposed to possess some other functional enhance-
  4661. ments. The exact details are not known to me at the time or writing. Anyone
  4662. possessing ECS information are requested to supply the requisite information
  4663. to the following address to allow me to maintain precise updates:
  4664.  
  4665.  
  4666.         Dave Edwards
  4667.         232 Hale Road
  4668.         WIDNES
  4669.         Cheshire
  4670.         WA8 8QA
  4671.  
  4672.  
  4673. The same applies to other DOC files in this series, which are also obtain-
  4674. able by sending a blank disc plus SAE for return postage to
  4675.  
  4676.  
  4677.         Mark Meany
  4678.         1 Cromwell Road
  4679.         Polygon
  4680.         SOUTHAMPTON
  4681.         Hants
  4682.         SO1 2JH
  4683.  
  4684.  
  4685. marking your envelope "CLUB DISC 4" and enclosing a covering letter explain-
  4686. ing your requirements. Other useful files and software are also available on
  4687. the various Club Discs from Mark above, and any back copies may be obtained
  4688. (assuming that archive copies still exist) by marking your envelope with the
  4689. legend "Club Disc N" where N is the disc number. Don't forget to include an
  4690. SAE or better still a jiffy bag for return postage, as neither he nor I are
  4691. rich enough to provide a freepost service!
  4692.  
  4693.  
  4694. Hardware:Logic Tutorial
  4695.  
  4696.  
  4697. For the mathematically minded, I present a logic tutorial allowing derivation
  4698. of minterms via the mechanism of developing alternational normal schemata to
  4699. create the individual minterm components.
  4700.  
  4701.     Conventions:In this tutorial, AB is used to represent A AND B, A + B
  4702. is used to represent A OR B, and b is used to represent NOT B. In an expres-
  4703. sion such as
  4704.  
  4705.         ABC + ABc + AbC
  4706.  
  4707. the AND operation takes precedence over the OR operation, and the NOT opera-
  4708. tion applies only to that letter typed in lower case. The expression (NOT B)
  4709. AND (NOT C) is represented by
  4710.  
  4711.         bc
  4712.  
  4713. and this list of conventions is thus complete.
  4714.  
  4715.  
  4716.     Rules:The following laws apply to all logical expressions:
  4717.  
  4718.     1) AB is the same as BA, and A + B is the same as B + A.
  4719.        This is the Commutative law.
  4720.  
  4721.     2) A(BC) and (AB)C are equivalent. Similarly, A + (B + C)
  4722.        is equivalent to (A + B) + C. This is the Associative
  4723.        law.
  4724.  
  4725.     3) The expression A(B+C) expands to AB + AC. This is the
  4726.        Distributive law of conjunction over alternation.
  4727.  
  4728.     4) The logical AND of any single term with an expression
  4729.        of the form (B + b) has no effect - this is the identity
  4730.        operation (equivalent to mutiplying numbers by 1). So
  4731.        A is equivalent to A(B+b) and further equivalent to
  4732.        A(B+b)(C+c).
  4733.  
  4734.  
  4735. These fundamental laws apply to many mathematical systems other than Boolean
  4736. Algebra, in particular they apply to the arithmetic of integers, rational
  4737. numbers and real numbers.
  4738.  
  4739.     Alternational Normal Schemata:This long-winded term describes any
  4740. logical expression which contains terms of the form ABC combined using the
  4741. OR operator. So the expression
  4742.  
  4743.     AB + ABc + ABCD + ABcD + Abcd
  4744.  
  4745. is an alternational normal schema, whereas
  4746.  
  4747.     (A+BC)D + ABCD
  4748.  
  4749. is not. The reason for the name is this:alternation is another name for the
  4750. OR operator in mathematical literature, and a normal schema is one in which
  4751. the format of the component terms obeys a strict set of rules.
  4752.  
  4753.     A DEVELOPED alternational normal schema is one where all of the com-
  4754. ponents contain the same number of component variables. The creation of a de-
  4755. veloped alternational normal schema involves scanning the expression for the
  4756. term with the maximum number of variables, and expand all terms deficient in
  4757. variables until all terms match in number of variables. An example:
  4758.  
  4759.     AB + C + b
  4760.  
  4761. becomes
  4762.  
  4763.     AB(C+c) + (A+a)(B+b)C + (A+a)b(C+c)
  4764.  
  4765. and then
  4766.  
  4767.     ABC + ABc + ABC + AbC + aBC + abC
  4768.  
  4769.     + AbC + Abc + abC + abc
  4770.  
  4771. Collecting together identical terms into single terms, and eliminating the
  4772. surplus terms, this becomes
  4773.  
  4774.     ABC + ABc + AbC + Abc + aBC + abC + abc
  4775.  
  4776. This is a devleoped alternational normal schema. All of the terms have the
  4777. same number of variables, and the expression is made up of terms of the form
  4778. ABC, all combined by alternation or the logical OR operation.
  4779.  
  4780.     Now, the connection between developed alternational schemata and
  4781. minterms is simple - they're one and the same. This tutorial is simply a dem-
  4782. onstration of a more formal method of derivation for those with the necessary
  4783. background. The example I have used to demonstrate the technique in action
  4784. was chosen deliberately to illustrate this connection. Basically, all that a
  4785. programmer does when picking minterms is an operation of the above kind, even
  4786. if using a more intuitive and less formal method.
  4787.  
  4788.  
  4789.  
  4790.  
  4791.  
  4792.